babylon.max.js 4.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979939809398193982939839398493985939869398793988939899399093991939929399393994939959399693997939989399994000940019400294003940049400594006940079400894009940109401194012940139401494015940169401794018940199402094021940229402394024940259402694027940289402994030940319403294033940349403594036940379403894039940409404194042940439404494045940469404794048940499405094051940529405394054940559405694057940589405994060940619406294063940649406594066940679406894069940709407194072940739407494075940769407794078940799408094081940829408394084940859408694087940889408994090940919409294093940949409594096940979409894099941009410194102941039410494105941069410794108941099411094111941129411394114941159411694117941189411994120941219412294123941249412594126941279412894129941309413194132941339413494135941369413794138941399414094141941429414394144941459414694147941489414994150941519415294153941549415594156941579415894159941609416194162941639416494165941669416794168941699417094171941729417394174941759417694177941789417994180941819418294183941849418594186941879418894189941909419194192941939419494195941969419794198941999420094201942029420394204942059420694207942089420994210942119421294213942149421594216942179421894219942209422194222942239422494225942269422794228942299423094231942329423394234942359423694237942389423994240942419424294243942449424594246942479424894249942509425194252942539425494255942569425794258942599426094261942629426394264942659426694267942689426994270942719427294273942749427594276942779427894279942809428194282942839428494285942869428794288942899429094291942929429394294942959429694297942989429994300943019430294303943049430594306943079430894309943109431194312943139431494315943169431794318943199432094321943229432394324943259432694327943289432994330943319433294333943349433594336943379433894339943409434194342943439434494345943469434794348943499435094351943529435394354943559435694357943589435994360943619436294363943649436594366943679436894369943709437194372943739437494375943769437794378943799438094381943829438394384943859438694387943889438994390943919439294393943949439594396943979439894399944009440194402944039440494405944069440794408944099441094411944129441394414944159441694417944189441994420944219442294423944249442594426944279442894429944309443194432944339443494435944369443794438944399444094441944429444394444944459444694447944489444994450944519445294453944549445594456944579445894459944609446194462944639446494465944669446794468944699447094471944729447394474944759447694477944789447994480944819448294483944849448594486944879448894489944909449194492944939449494495944969449794498944999450094501945029450394504945059450694507945089450994510945119451294513945149451594516945179451894519945209452194522945239452494525945269452794528945299453094531945329453394534945359453694537945389453994540945419454294543945449454594546945479454894549945509455194552945539455494555945569455794558945599456094561945629456394564945659456694567945689456994570945719457294573945749457594576945779457894579945809458194582945839458494585945869458794588945899459094591945929459394594945959459694597945989459994600946019460294603946049460594606946079460894609946109461194612946139461494615946169461794618946199462094621946229462394624946259462694627946289462994630946319463294633946349463594636946379463894639946409464194642946439464494645946469464794648946499465094651946529465394654946559465694657946589465994660946619466294663946649466594666946679466894669946709467194672946739467494675946769467794678946799468094681946829468394684946859468694687946889468994690946919469294693946949469594696946979469894699947009470194702947039470494705947069470794708947099471094711947129471394714947159471694717947189471994720947219472294723947249472594726947279472894729947309473194732947339473494735947369473794738947399474094741947429474394744947459474694747947489474994750947519475294753947549475594756947579475894759947609476194762947639476494765947669476794768947699477094771947729477394774947759477694777947789477994780947819478294783947849478594786947879478894789947909479194792947939479494795947969479794798947999480094801948029480394804948059480694807948089480994810948119481294813948149481594816948179481894819948209482194822948239482494825948269482794828948299483094831948329483394834948359483694837948389483994840948419484294843948449484594846948479484894849948509485194852948539485494855948569485794858948599486094861948629486394864948659486694867948689486994870948719487294873948749487594876948779487894879948809488194882948839488494885948869488794888948899489094891948929489394894948959489694897948989489994900949019490294903949049490594906949079490894909949109491194912949139491494915949169491794918949199492094921949229492394924949259492694927949289492994930949319493294933949349493594936949379493894939949409494194942949439494494945949469494794948949499495094951949529495394954949559495694957949589495994960949619496294963949649496594966949679496894969949709497194972949739497494975949769497794978949799498094981949829498394984949859498694987949889498994990949919499294993949949499594996949979499894999950009500195002950039500495005950069500795008950099501095011950129501395014950159501695017950189501995020950219502295023950249502595026950279502895029950309503195032950339503495035950369503795038950399504095041950429504395044950459504695047950489504995050950519505295053950549505595056950579505895059950609506195062950639506495065950669506795068950699507095071950729507395074950759507695077950789507995080950819508295083950849508595086950879508895089950909509195092950939509495095950969509795098950999510095101951029510395104951059510695107951089510995110951119511295113951149511595116951179511895119951209512195122951239512495125951269512795128951299513095131951329513395134951359513695137951389513995140951419514295143951449514595146951479514895149951509515195152951539515495155951569515795158951599516095161951629516395164951659516695167951689516995170951719517295173951749517595176951779517895179951809518195182951839518495185951869518795188951899519095191951929519395194951959519695197951989519995200952019520295203952049520595206952079520895209952109521195212952139521495215952169521795218952199522095221952229522395224952259522695227952289522995230952319523295233952349523595236952379523895239952409524195242952439524495245952469524795248952499525095251952529525395254952559525695257952589525995260952619526295263952649526595266952679526895269952709527195272952739527495275952769527795278952799528095281952829528395284952859528695287952889528995290952919529295293952949529595296952979529895299953009530195302953039530495305953069530795308953099531095311953129531395314953159531695317953189531995320953219532295323953249532595326953279532895329953309533195332953339533495335953369533795338953399534095341953429534395344953459534695347953489534995350953519535295353953549535595356953579535895359953609536195362953639536495365953669536795368953699537095371953729537395374953759537695377953789537995380953819538295383953849538595386953879538895389953909539195392953939539495395953969539795398953999540095401954029540395404954059540695407954089540995410954119541295413954149541595416954179541895419954209542195422954239542495425954269542795428954299543095431954329543395434954359543695437954389543995440954419544295443954449544595446954479544895449954509545195452954539545495455954569545795458954599546095461954629546395464954659546695467954689546995470954719547295473954749547595476954779547895479954809548195482954839548495485954869548795488954899549095491954929549395494954959549695497954989549995500955019550295503955049550595506955079550895509955109551195512955139551495515955169551795518955199552095521955229552395524955259552695527955289552995530955319553295533955349553595536955379553895539955409554195542955439554495545955469554795548955499555095551955529555395554955559555695557955589555995560955619556295563955649556595566955679556895569955709557195572955739557495575955769557795578955799558095581955829558395584955859558695587955889558995590955919559295593955949559595596955979559895599956009560195602956039560495605956069560795608956099561095611956129561395614956159561695617956189561995620956219562295623956249562595626956279562895629956309563195632956339563495635956369563795638956399564095641956429564395644956459564695647956489564995650956519565295653956549565595656956579565895659956609566195662956639566495665956669566795668956699567095671956729567395674956759567695677956789567995680956819568295683956849568595686956879568895689956909569195692956939569495695956969569795698956999570095701957029570395704957059570695707957089570995710957119571295713957149571595716957179571895719957209572195722957239572495725957269572795728957299573095731957329573395734957359573695737957389573995740957419574295743957449574595746957479574895749957509575195752957539575495755957569575795758957599576095761957629576395764957659576695767957689576995770957719577295773957749577595776957779577895779957809578195782957839578495785957869578795788957899579095791957929579395794957959579695797957989579995800958019580295803958049580595806958079580895809958109581195812958139581495815958169581795818958199582095821958229582395824958259582695827958289582995830958319583295833958349583595836958379583895839958409584195842958439584495845958469584795848958499585095851958529585395854958559585695857958589585995860958619586295863958649586595866958679586895869958709587195872958739587495875958769587795878958799588095881958829588395884958859588695887958889588995890958919589295893958949589595896958979589895899959009590195902959039590495905959069590795908959099591095911959129591395914959159591695917959189591995920959219592295923959249592595926959279592895929959309593195932959339593495935959369593795938959399594095941959429594395944959459594695947959489594995950959519595295953959549595595956959579595895959959609596195962959639596495965959669596795968959699597095971959729597395974959759597695977959789597995980959819598295983959849598595986959879598895989959909599195992959939599495995959969599795998959999600096001960029600396004960059600696007960089600996010960119601296013960149601596016960179601896019960209602196022960239602496025960269602796028960299603096031960329603396034960359603696037960389603996040960419604296043960449604596046960479604896049960509605196052960539605496055960569605796058960599606096061960629606396064960659606696067960689606996070960719607296073960749607596076960779607896079960809608196082960839608496085960869608796088960899609096091960929609396094960959609696097960989609996100961019610296103961049610596106961079610896109961109611196112961139611496115961169611796118961199612096121961229612396124961259612696127961289612996130961319613296133961349613596136961379613896139961409614196142961439614496145961469614796148961499615096151961529615396154961559615696157961589615996160961619616296163961649616596166961679616896169961709617196172961739617496175961769617796178961799618096181961829618396184961859618696187961889618996190961919619296193961949619596196961979619896199962009620196202962039620496205962069620796208962099621096211962129621396214962159621696217962189621996220962219622296223962249622596226962279622896229962309623196232962339623496235962369623796238962399624096241962429624396244962459624696247962489624996250962519625296253962549625596256962579625896259962609626196262962639626496265962669626796268962699627096271962729627396274962759627696277962789627996280962819628296283962849628596286962879628896289962909629196292962939629496295962969629796298962999630096301963029630396304963059630696307963089630996310963119631296313963149631596316963179631896319963209632196322963239632496325963269632796328963299633096331963329633396334963359633696337963389633996340963419634296343963449634596346963479634896349963509635196352963539635496355963569635796358963599636096361963629636396364963659636696367963689636996370963719637296373963749637596376963779637896379963809638196382963839638496385963869638796388963899639096391963929639396394963959639696397963989639996400964019640296403964049640596406964079640896409964109641196412964139641496415964169641796418964199642096421964229642396424964259642696427964289642996430964319643296433964349643596436964379643896439964409644196442964439644496445964469644796448964499645096451964529645396454964559645696457964589645996460964619646296463964649646596466964679646896469964709647196472964739647496475964769647796478964799648096481964829648396484964859648696487964889648996490964919649296493964949649596496964979649896499965009650196502965039650496505965069650796508965099651096511965129651396514965159651696517965189651996520965219652296523965249652596526965279652896529965309653196532965339653496535965369653796538965399654096541965429654396544965459654696547965489654996550965519655296553965549655596556965579655896559965609656196562965639656496565965669656796568965699657096571965729657396574965759657696577965789657996580965819658296583965849658596586965879658896589965909659196592965939659496595965969659796598965999660096601966029660396604966059660696607966089660996610966119661296613966149661596616966179661896619966209662196622966239662496625966269662796628966299663096631966329663396634966359663696637966389663996640966419664296643966449664596646966479664896649966509665196652966539665496655966569665796658966599666096661966629666396664966659666696667966689666996670966719667296673966749667596676966779667896679966809668196682966839668496685966869668796688966899669096691966929669396694966959669696697966989669996700967019670296703967049670596706967079670896709967109671196712967139671496715967169671796718967199672096721967229672396724967259672696727967289672996730967319673296733967349673596736967379673896739967409674196742967439674496745967469674796748967499675096751967529675396754967559675696757967589675996760967619676296763967649676596766967679676896769967709677196772967739677496775967769677796778967799678096781967829678396784967859678696787967889678996790967919679296793967949679596796967979679896799968009680196802968039680496805968069680796808968099681096811968129681396814968159681696817968189681996820968219682296823968249682596826968279682896829968309683196832968339683496835968369683796838968399684096841968429684396844968459684696847968489684996850968519685296853968549685596856968579685896859968609686196862968639686496865968669686796868968699687096871968729687396874968759687696877968789687996880968819688296883968849688596886968879688896889968909689196892968939689496895968969689796898968999690096901969029690396904969059690696907969089690996910969119691296913969149691596916969179691896919969209692196922969239692496925969269692796928969299693096931969329693396934969359693696937969389693996940969419694296943969449694596946969479694896949969509695196952969539695496955969569695796958969599696096961969629696396964969659696696967969689696996970969719697296973969749697596976969779697896979969809698196982969839698496985969869698796988969899699096991969929699396994969959699696997969989699997000970019700297003970049700597006970079700897009970109701197012970139701497015970169701797018970199702097021970229702397024970259702697027970289702997030970319703297033970349703597036970379703897039970409704197042970439704497045970469704797048970499705097051970529705397054970559705697057970589705997060970619706297063970649706597066970679706897069970709707197072970739707497075970769707797078970799708097081970829708397084970859708697087970889708997090970919709297093970949709597096970979709897099971009710197102971039710497105971069710797108971099711097111971129711397114971159711697117971189711997120971219712297123971249712597126971279712897129971309713197132971339713497135971369713797138971399714097141971429714397144971459714697147971489714997150971519715297153971549715597156971579715897159971609716197162971639716497165971669716797168971699717097171971729717397174971759717697177971789717997180971819718297183971849718597186971879718897189971909719197192971939719497195971969719797198971999720097201972029720397204972059720697207972089720997210972119721297213972149721597216972179721897219972209722197222972239722497225972269722797228972299723097231972329723397234972359723697237972389723997240972419724297243972449724597246972479724897249972509725197252972539725497255972569725797258972599726097261972629726397264972659726697267972689726997270972719727297273972749727597276972779727897279972809728197282972839728497285972869728797288972899729097291972929729397294972959729697297972989729997300973019730297303973049730597306973079730897309973109731197312973139731497315973169731797318973199732097321973229732397324973259732697327973289732997330973319733297333973349733597336973379733897339973409734197342973439734497345973469734797348973499735097351973529735397354973559735697357973589735997360973619736297363973649736597366973679736897369973709737197372973739737497375973769737797378973799738097381973829738397384973859738697387973889738997390973919739297393973949739597396973979739897399974009740197402974039740497405974069740797408974099741097411974129741397414974159741697417974189741997420974219742297423974249742597426974279742897429974309743197432974339743497435974369743797438974399744097441974429744397444974459744697447974489744997450974519745297453974549745597456974579745897459974609746197462974639746497465974669746797468974699747097471974729747397474974759747697477974789747997480974819748297483974849748597486974879748897489974909749197492974939749497495974969749797498974999750097501975029750397504975059750697507975089750997510975119751297513975149751597516975179751897519975209752197522975239752497525975269752797528975299753097531975329753397534975359753697537975389753997540975419754297543975449754597546975479754897549975509755197552975539755497555975569755797558975599756097561975629756397564975659756697567975689756997570975719757297573975749757597576975779757897579975809758197582975839758497585975869758797588975899759097591975929759397594975959759697597975989759997600976019760297603976049760597606976079760897609976109761197612976139761497615976169761797618976199762097621976229762397624976259762697627976289762997630976319763297633976349763597636976379763897639976409764197642976439764497645976469764797648976499765097651976529765397654976559765697657976589765997660976619766297663976649766597666976679766897669976709767197672976739767497675976769767797678976799768097681976829768397684976859768697687976889768997690976919769297693976949769597696976979769897699977009770197702977039770497705977069770797708977099771097711977129771397714977159771697717977189771997720977219772297723977249772597726977279772897729977309773197732977339773497735977369773797738977399774097741977429774397744977459774697747977489774997750977519775297753977549775597756977579775897759977609776197762977639776497765977669776797768977699777097771977729777397774977759777697777977789777997780977819778297783977849778597786977879778897789977909779197792977939779497795977969779797798977999780097801978029780397804978059780697807978089780997810978119781297813978149781597816978179781897819978209782197822978239782497825978269782797828978299783097831978329783397834978359783697837978389783997840978419784297843978449784597846978479784897849978509785197852978539785497855978569785797858978599786097861978629786397864978659786697867978689786997870978719787297873978749787597876978779787897879978809788197882978839788497885978869788797888978899789097891978929789397894978959789697897978989789997900979019790297903979049790597906979079790897909979109791197912979139791497915979169791797918979199792097921979229792397924979259792697927979289792997930979319793297933979349793597936979379793897939979409794197942979439794497945979469794797948979499795097951979529795397954979559795697957979589795997960979619796297963979649796597966979679796897969979709797197972979739797497975979769797797978979799798097981979829798397984979859798697987979889798997990979919799297993979949799597996979979799897999980009800198002980039800498005980069800798008980099801098011980129801398014980159801698017980189801998020980219802298023980249802598026980279802898029980309803198032980339803498035980369803798038980399804098041980429804398044980459804698047980489804998050980519805298053980549805598056980579805898059980609806198062980639806498065980669806798068980699807098071980729807398074980759807698077980789807998080980819808298083980849808598086980879808898089980909809198092980939809498095980969809798098980999810098101981029810398104981059810698107981089810998110981119811298113981149811598116981179811898119981209812198122981239812498125981269812798128981299813098131981329813398134981359813698137981389813998140981419814298143981449814598146981479814898149981509815198152981539815498155981569815798158981599816098161981629816398164981659816698167981689816998170981719817298173981749817598176981779817898179981809818198182981839818498185981869818798188981899819098191981929819398194981959819698197981989819998200982019820298203982049820598206982079820898209982109821198212982139821498215982169821798218982199822098221982229822398224982259822698227982289822998230982319823298233982349823598236982379823898239982409824198242982439824498245982469824798248982499825098251982529825398254982559825698257982589825998260982619826298263982649826598266982679826898269982709827198272982739827498275982769827798278982799828098281982829828398284982859828698287982889828998290982919829298293982949829598296982979829898299983009830198302983039830498305983069830798308983099831098311983129831398314983159831698317983189831998320983219832298323983249832598326983279832898329983309833198332983339833498335983369833798338983399834098341983429834398344983459834698347983489834998350983519835298353983549835598356983579835898359983609836198362983639836498365983669836798368983699837098371983729837398374983759837698377983789837998380983819838298383983849838598386983879838898389983909839198392983939839498395983969839798398983999840098401984029840398404984059840698407984089840998410984119841298413984149841598416984179841898419984209842198422984239842498425984269842798428984299843098431984329843398434984359843698437984389843998440984419844298443984449844598446984479844898449984509845198452984539845498455984569845798458984599846098461984629846398464984659846698467984689846998470984719847298473984749847598476984779847898479984809848198482984839848498485984869848798488984899849098491984929849398494984959849698497984989849998500985019850298503985049850598506985079850898509985109851198512985139851498515985169851798518985199852098521985229852398524985259852698527985289852998530985319853298533985349853598536985379853898539985409854198542985439854498545985469854798548985499855098551985529855398554985559855698557985589855998560985619856298563985649856598566985679856898569985709857198572985739857498575985769857798578985799858098581985829858398584985859858698587985889858998590985919859298593985949859598596985979859898599986009860198602986039860498605986069860798608986099861098611986129861398614986159861698617986189861998620986219862298623986249862598626986279862898629986309863198632986339863498635986369863798638986399864098641986429864398644986459864698647986489864998650986519865298653986549865598656986579865898659986609866198662986639866498665986669866798668986699867098671986729867398674986759867698677986789867998680986819868298683986849868598686986879868898689986909869198692986939869498695986969869798698986999870098701987029870398704987059870698707987089870998710987119871298713987149871598716987179871898719987209872198722987239872498725987269872798728987299873098731987329873398734987359873698737987389873998740987419874298743987449874598746987479874898749987509875198752987539875498755987569875798758987599876098761987629876398764987659876698767987689876998770987719877298773987749877598776987779877898779987809878198782987839878498785987869878798788987899879098791987929879398794987959879698797987989879998800988019880298803988049880598806988079880898809988109881198812988139881498815988169881798818988199882098821988229882398824988259882698827988289882998830988319883298833988349883598836988379883898839988409884198842988439884498845988469884798848988499885098851988529885398854988559885698857988589885998860988619886298863988649886598866988679886898869988709887198872988739887498875988769887798878988799888098881988829888398884988859888698887988889888998890988919889298893988949889598896988979889898899989009890198902989039890498905989069890798908989099891098911989129891398914989159891698917989189891998920989219892298923989249892598926989279892898929989309893198932989339893498935989369893798938989399894098941989429894398944989459894698947989489894998950989519895298953989549895598956989579895898959989609896198962989639896498965989669896798968989699897098971989729897398974989759897698977989789897998980989819898298983989849898598986989879898898989989909899198992989939899498995989969899798998989999900099001990029900399004990059900699007990089900999010990119901299013990149901599016990179901899019990209902199022990239902499025990269902799028990299903099031990329903399034990359903699037990389903999040990419904299043990449904599046990479904899049990509905199052990539905499055990569905799058990599906099061990629906399064990659906699067990689906999070990719907299073990749907599076
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /**
  186. * Observable that will be called when effect is bound.
  187. */
  188. this.onBindObservable = new BABYLON.Observable();
  189. /** @hidden */
  190. this._bonesComputationForcedToCPU = false;
  191. this._uniformBuffersNames = {};
  192. this._isReady = false;
  193. this._compilationError = "";
  194. this.name = baseName;
  195. if (attributesNamesOrOptions.attributes) {
  196. var options = attributesNamesOrOptions;
  197. this._engine = uniformsNamesOrEngine;
  198. this._attributesNames = options.attributes;
  199. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  200. this._samplers = options.samplers.slice();
  201. this.defines = options.defines;
  202. this.onError = options.onError;
  203. this.onCompiled = options.onCompiled;
  204. this._fallbacks = options.fallbacks;
  205. this._indexParameters = options.indexParameters;
  206. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  207. if (options.uniformBuffersNames) {
  208. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  209. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  210. }
  211. }
  212. }
  213. else {
  214. this._engine = engine;
  215. this.defines = defines;
  216. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  217. this._samplers = samplers ? samplers.slice() : [];
  218. this._attributesNames = attributesNamesOrOptions;
  219. this.onError = onError;
  220. this.onCompiled = onCompiled;
  221. this._indexParameters = indexParameters;
  222. this._fallbacks = fallbacks;
  223. }
  224. this.uniqueId = Effect._uniqueIdSeed++;
  225. var vertexSource;
  226. var fragmentSource;
  227. if (baseName.vertexElement) {
  228. vertexSource = document.getElementById(baseName.vertexElement);
  229. if (!vertexSource) {
  230. vertexSource = baseName.vertexElement;
  231. }
  232. }
  233. else {
  234. vertexSource = baseName.vertex || baseName;
  235. }
  236. if (baseName.fragmentElement) {
  237. fragmentSource = document.getElementById(baseName.fragmentElement);
  238. if (!fragmentSource) {
  239. fragmentSource = baseName.fragmentElement;
  240. }
  241. }
  242. else {
  243. fragmentSource = baseName.fragment || baseName;
  244. }
  245. this._loadVertexShader(vertexSource, function (vertexCode) {
  246. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  247. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  248. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  249. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  250. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  251. if (baseName) {
  252. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  253. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  254. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  255. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  256. }
  257. else {
  258. _this._vertexSourceCode = migratedVertexCode;
  259. _this._fragmentSourceCode = migratedFragmentCode;
  260. }
  261. _this._prepareEffect();
  262. });
  263. });
  264. });
  265. });
  266. });
  267. });
  268. }
  269. Object.defineProperty(Effect.prototype, "key", {
  270. /**
  271. * Unique key for this effect
  272. */
  273. get: function () {
  274. return this._key;
  275. },
  276. enumerable: true,
  277. configurable: true
  278. });
  279. /**
  280. * If the effect has been compiled and prepared.
  281. * @returns if the effect is compiled and prepared.
  282. */
  283. Effect.prototype.isReady = function () {
  284. return this._isReady;
  285. };
  286. /**
  287. * The engine the effect was initialized with.
  288. * @returns the engine.
  289. */
  290. Effect.prototype.getEngine = function () {
  291. return this._engine;
  292. };
  293. /**
  294. * The compiled webGL program for the effect
  295. * @returns the webGL program.
  296. */
  297. Effect.prototype.getProgram = function () {
  298. return this._program;
  299. };
  300. /**
  301. * The set of names of attribute variables for the shader.
  302. * @returns An array of attribute names.
  303. */
  304. Effect.prototype.getAttributesNames = function () {
  305. return this._attributesNames;
  306. };
  307. /**
  308. * Returns the attribute at the given index.
  309. * @param index The index of the attribute.
  310. * @returns The location of the attribute.
  311. */
  312. Effect.prototype.getAttributeLocation = function (index) {
  313. return this._attributes[index];
  314. };
  315. /**
  316. * Returns the attribute based on the name of the variable.
  317. * @param name of the attribute to look up.
  318. * @returns the attribute location.
  319. */
  320. Effect.prototype.getAttributeLocationByName = function (name) {
  321. var index = this._attributesNames.indexOf(name);
  322. return this._attributes[index];
  323. };
  324. /**
  325. * The number of attributes.
  326. * @returns the numnber of attributes.
  327. */
  328. Effect.prototype.getAttributesCount = function () {
  329. return this._attributes.length;
  330. };
  331. /**
  332. * Gets the index of a uniform variable.
  333. * @param uniformName of the uniform to look up.
  334. * @returns the index.
  335. */
  336. Effect.prototype.getUniformIndex = function (uniformName) {
  337. return this._uniformsNames.indexOf(uniformName);
  338. };
  339. /**
  340. * Returns the attribute based on the name of the variable.
  341. * @param uniformName of the uniform to look up.
  342. * @returns the location of the uniform.
  343. */
  344. Effect.prototype.getUniform = function (uniformName) {
  345. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  346. };
  347. /**
  348. * Returns an array of sampler variable names
  349. * @returns The array of sampler variable neames.
  350. */
  351. Effect.prototype.getSamplers = function () {
  352. return this._samplers;
  353. };
  354. /**
  355. * The error from the last compilation.
  356. * @returns the error string.
  357. */
  358. Effect.prototype.getCompilationError = function () {
  359. return this._compilationError;
  360. };
  361. /**
  362. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  363. * @param func The callback to be used.
  364. */
  365. Effect.prototype.executeWhenCompiled = function (func) {
  366. if (this.isReady()) {
  367. func(this);
  368. return;
  369. }
  370. this.onCompileObservable.add(function (effect) {
  371. func(effect);
  372. });
  373. };
  374. /** @hidden */
  375. Effect.prototype._loadVertexShader = function (vertex, callback) {
  376. if (BABYLON.Tools.IsWindowObjectExist()) {
  377. // DOM element ?
  378. if (vertex instanceof HTMLElement) {
  379. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  380. callback(vertexCode);
  381. return;
  382. }
  383. }
  384. // Base64 encoded ?
  385. if (vertex.substr(0, 7) === "base64:") {
  386. var vertexBinary = window.atob(vertex.substr(7));
  387. callback(vertexBinary);
  388. return;
  389. }
  390. // Is in local store ?
  391. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  392. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  393. return;
  394. }
  395. var vertexShaderUrl;
  396. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  397. vertexShaderUrl = vertex;
  398. }
  399. else {
  400. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  401. }
  402. // Vertex shader
  403. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  404. };
  405. /** @hidden */
  406. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  407. if (BABYLON.Tools.IsWindowObjectExist()) {
  408. // DOM element ?
  409. if (fragment instanceof HTMLElement) {
  410. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  411. callback(fragmentCode);
  412. return;
  413. }
  414. }
  415. // Base64 encoded ?
  416. if (fragment.substr(0, 7) === "base64:") {
  417. var fragmentBinary = window.atob(fragment.substr(7));
  418. callback(fragmentBinary);
  419. return;
  420. }
  421. // Is in local store ?
  422. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  423. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  424. return;
  425. }
  426. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  427. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  428. return;
  429. }
  430. var fragmentShaderUrl;
  431. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  432. fragmentShaderUrl = fragment;
  433. }
  434. else {
  435. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  436. }
  437. // Fragment shader
  438. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  439. };
  440. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  441. // Rebuild shaders source code
  442. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  443. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  444. vertexCode = prefix + vertexCode;
  445. fragmentCode = prefix + fragmentCode;
  446. // Number lines of shaders source code
  447. var i = 2;
  448. var regex = /\n/gm;
  449. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  450. i = 2;
  451. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  452. // Dump shaders name and formatted source code
  453. if (this.name.vertexElement) {
  454. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  455. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  456. }
  457. else if (this.name.vertex) {
  458. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  459. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  460. }
  461. else {
  462. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  463. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  464. }
  465. };
  466. ;
  467. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  468. var preparedSourceCode = this._processPrecision(sourceCode);
  469. if (this._engine.webGLVersion == 1) {
  470. callback(preparedSourceCode);
  471. return;
  472. }
  473. // Already converted
  474. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  475. callback(preparedSourceCode.replace("#version 300 es", ""));
  476. return;
  477. }
  478. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  479. // Remove extensions
  480. // #extension GL_OES_standard_derivatives : enable
  481. // #extension GL_EXT_shader_texture_lod : enable
  482. // #extension GL_EXT_frag_depth : enable
  483. // #extension GL_EXT_draw_buffers : require
  484. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  485. var result = preparedSourceCode.replace(regex, "");
  486. // Migrate to GLSL v300
  487. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  488. result = result.replace(/attribute[ \t]/g, "in ");
  489. result = result.replace(/[ \t]attribute/g, " in");
  490. if (isFragment) {
  491. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  492. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  493. result = result.replace(/texture2D\s*\(/g, "texture(");
  494. result = result.replace(/textureCube\s*\(/g, "texture(");
  495. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  496. result = result.replace(/gl_FragColor/g, "glFragColor");
  497. result = result.replace(/gl_FragData/g, "glFragData");
  498. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  499. }
  500. callback(result);
  501. };
  502. Effect.prototype._processIncludes = function (sourceCode, callback) {
  503. var _this = this;
  504. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  505. var match = regex.exec(sourceCode);
  506. var returnValue = new String(sourceCode);
  507. while (match != null) {
  508. var includeFile = match[1];
  509. // Uniform declaration
  510. if (includeFile.indexOf("__decl__") !== -1) {
  511. includeFile = includeFile.replace(/__decl__/, "");
  512. if (this._engine.supportsUniformBuffers) {
  513. includeFile = includeFile.replace(/Vertex/, "Ubo");
  514. includeFile = includeFile.replace(/Fragment/, "Ubo");
  515. }
  516. includeFile = includeFile + "Declaration";
  517. }
  518. if (Effect.IncludesShadersStore[includeFile]) {
  519. // Substitution
  520. var includeContent = Effect.IncludesShadersStore[includeFile];
  521. if (match[2]) {
  522. var splits = match[3].split(",");
  523. for (var index = 0; index < splits.length; index += 2) {
  524. var source = new RegExp(splits[index], "g");
  525. var dest = splits[index + 1];
  526. includeContent = includeContent.replace(source, dest);
  527. }
  528. }
  529. if (match[4]) {
  530. var indexString = match[5];
  531. if (indexString.indexOf("..") !== -1) {
  532. var indexSplits = indexString.split("..");
  533. var minIndex = parseInt(indexSplits[0]);
  534. var maxIndex = parseInt(indexSplits[1]);
  535. var sourceIncludeContent = includeContent.slice(0);
  536. includeContent = "";
  537. if (isNaN(maxIndex)) {
  538. maxIndex = this._indexParameters[indexSplits[1]];
  539. }
  540. for (var i = minIndex; i < maxIndex; i++) {
  541. if (!this._engine.supportsUniformBuffers) {
  542. // Ubo replacement
  543. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  544. return p1 + "{X}";
  545. });
  546. }
  547. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  548. }
  549. }
  550. else {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent = includeContent.replace(/\{X\}/g, indexString);
  558. }
  559. }
  560. // Replace
  561. returnValue = returnValue.replace(match[0], includeContent);
  562. }
  563. else {
  564. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  565. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  566. Effect.IncludesShadersStore[includeFile] = fileContent;
  567. _this._processIncludes(returnValue, callback);
  568. });
  569. return;
  570. }
  571. match = regex.exec(sourceCode);
  572. }
  573. callback(returnValue);
  574. };
  575. Effect.prototype._processPrecision = function (source) {
  576. if (source.indexOf("precision highp float") === -1) {
  577. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  578. source = "precision mediump float;\n" + source;
  579. }
  580. else {
  581. source = "precision highp float;\n" + source;
  582. }
  583. }
  584. else {
  585. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  586. source = source.replace("precision highp float", "precision mediump float");
  587. }
  588. }
  589. return source;
  590. };
  591. /**
  592. * Recompiles the webGL program
  593. * @param vertexSourceCode The source code for the vertex shader.
  594. * @param fragmentSourceCode The source code for the fragment shader.
  595. * @param onCompiled Callback called when completed.
  596. * @param onError Callback called on error.
  597. */
  598. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  599. var _this = this;
  600. this._isReady = false;
  601. this._vertexSourceCodeOverride = vertexSourceCode;
  602. this._fragmentSourceCodeOverride = fragmentSourceCode;
  603. this.onError = function (effect, error) {
  604. if (onError) {
  605. onError(error);
  606. }
  607. };
  608. this.onCompiled = function () {
  609. var scenes = _this.getEngine().scenes;
  610. for (var i = 0; i < scenes.length; i++) {
  611. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  612. }
  613. if (onCompiled) {
  614. onCompiled(_this._program);
  615. }
  616. };
  617. this._fallbacks = null;
  618. this._prepareEffect();
  619. };
  620. /**
  621. * Gets the uniform locations of the the specified variable names
  622. * @param names THe names of the variables to lookup.
  623. * @returns Array of locations in the same order as variable names.
  624. */
  625. Effect.prototype.getSpecificUniformLocations = function (names) {
  626. var engine = this._engine;
  627. return engine.getUniforms(this._program, names);
  628. };
  629. /**
  630. * Prepares the effect
  631. */
  632. Effect.prototype._prepareEffect = function () {
  633. var attributesNames = this._attributesNames;
  634. var defines = this.defines;
  635. var fallbacks = this._fallbacks;
  636. this._valueCache = {};
  637. var previousProgram = this._program;
  638. try {
  639. var engine = this._engine;
  640. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  641. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  642. }
  643. else {
  644. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  645. }
  646. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  647. if (engine.supportsUniformBuffers) {
  648. for (var name in this._uniformBuffersNames) {
  649. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  650. }
  651. }
  652. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  653. this._attributes = engine.getAttributes(this._program, attributesNames);
  654. var index;
  655. for (index = 0; index < this._samplers.length; index++) {
  656. var sampler = this.getUniform(this._samplers[index]);
  657. if (sampler == null) {
  658. this._samplers.splice(index, 1);
  659. index--;
  660. }
  661. }
  662. engine.bindSamplers(this);
  663. this._compilationError = "";
  664. this._isReady = true;
  665. if (this.onCompiled) {
  666. this.onCompiled(this);
  667. }
  668. this.onCompileObservable.notifyObservers(this);
  669. this.onCompileObservable.clear();
  670. // Unbind mesh reference in fallbacks
  671. if (this._fallbacks) {
  672. this._fallbacks.unBindMesh();
  673. }
  674. if (previousProgram) {
  675. this.getEngine()._deleteProgram(previousProgram);
  676. }
  677. }
  678. catch (e) {
  679. this._compilationError = e.message;
  680. // Let's go through fallbacks then
  681. BABYLON.Tools.Error("Unable to compile effect:");
  682. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  683. return " " + uniform;
  684. }));
  685. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  686. return " " + attribute;
  687. }));
  688. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  689. BABYLON.Tools.Error("Error: " + this._compilationError);
  690. if (previousProgram) {
  691. this._program = previousProgram;
  692. this._isReady = true;
  693. if (this.onError) {
  694. this.onError(this, this._compilationError);
  695. }
  696. this.onErrorObservable.notifyObservers(this);
  697. }
  698. if (fallbacks && fallbacks.isMoreFallbacks) {
  699. BABYLON.Tools.Error("Trying next fallback.");
  700. this.defines = fallbacks.reduce(this.defines, this);
  701. this._prepareEffect();
  702. }
  703. else { // Sorry we did everything we can
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. this.onErrorObservable.clear();
  709. // Unbind mesh reference in fallbacks
  710. if (this._fallbacks) {
  711. this._fallbacks.unBindMesh();
  712. }
  713. }
  714. }
  715. };
  716. Object.defineProperty(Effect.prototype, "isSupported", {
  717. /**
  718. * Checks if the effect is supported. (Must be called after compilation)
  719. */
  720. get: function () {
  721. return this._compilationError === "";
  722. },
  723. enumerable: true,
  724. configurable: true
  725. });
  726. /**
  727. * Binds a texture to the engine to be used as output of the shader.
  728. * @param channel Name of the output variable.
  729. * @param texture Texture to bind.
  730. */
  731. Effect.prototype._bindTexture = function (channel, texture) {
  732. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  733. };
  734. /**
  735. * Sets a texture on the engine to be used in the shader.
  736. * @param channel Name of the sampler variable.
  737. * @param texture Texture to set.
  738. */
  739. Effect.prototype.setTexture = function (channel, texture) {
  740. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  741. };
  742. /**
  743. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  744. * @param channel Name of the sampler variable.
  745. * @param texture Texture to set.
  746. */
  747. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  748. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  749. };
  750. /**
  751. * Sets an array of textures on the engine to be used in the shader.
  752. * @param channel Name of the variable.
  753. * @param textures Textures to set.
  754. */
  755. Effect.prototype.setTextureArray = function (channel, textures) {
  756. if (this._samplers.indexOf(channel + "Ex") === -1) {
  757. var initialPos = this._samplers.indexOf(channel);
  758. for (var index = 1; index < textures.length; index++) {
  759. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  760. }
  761. }
  762. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  763. };
  764. /**
  765. * 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)
  766. * @param channel Name of the sampler variable.
  767. * @param postProcess Post process to get the input texture from.
  768. */
  769. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  770. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  771. };
  772. /**
  773. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  774. * 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)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the output texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /** @hidden */
  782. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  783. var cache = this._valueCache[uniformName];
  784. var flag = matrix.updateFlag;
  785. if (cache !== undefined && cache === flag) {
  786. return false;
  787. }
  788. this._valueCache[uniformName] = flag;
  789. return true;
  790. };
  791. /** @hidden */
  792. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  793. var cache = this._valueCache[uniformName];
  794. if (!cache) {
  795. cache = [x, y];
  796. this._valueCache[uniformName] = cache;
  797. return true;
  798. }
  799. var changed = false;
  800. if (cache[0] !== x) {
  801. cache[0] = x;
  802. changed = true;
  803. }
  804. if (cache[1] !== y) {
  805. cache[1] = y;
  806. changed = true;
  807. }
  808. return changed;
  809. };
  810. /** @hidden */
  811. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  812. var cache = this._valueCache[uniformName];
  813. if (!cache) {
  814. cache = [x, y, z];
  815. this._valueCache[uniformName] = cache;
  816. return true;
  817. }
  818. var changed = false;
  819. if (cache[0] !== x) {
  820. cache[0] = x;
  821. changed = true;
  822. }
  823. if (cache[1] !== y) {
  824. cache[1] = y;
  825. changed = true;
  826. }
  827. if (cache[2] !== z) {
  828. cache[2] = z;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /** @hidden */
  834. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  835. var cache = this._valueCache[uniformName];
  836. if (!cache) {
  837. cache = [x, y, z, w];
  838. this._valueCache[uniformName] = cache;
  839. return true;
  840. }
  841. var changed = false;
  842. if (cache[0] !== x) {
  843. cache[0] = x;
  844. changed = true;
  845. }
  846. if (cache[1] !== y) {
  847. cache[1] = y;
  848. changed = true;
  849. }
  850. if (cache[2] !== z) {
  851. cache[2] = z;
  852. changed = true;
  853. }
  854. if (cache[3] !== w) {
  855. cache[3] = w;
  856. changed = true;
  857. }
  858. return changed;
  859. };
  860. /**
  861. * Binds a buffer to a uniform.
  862. * @param buffer Buffer to bind.
  863. * @param name Name of the uniform variable to bind to.
  864. */
  865. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  866. var bufferName = this._uniformBuffersNames[name];
  867. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  868. return;
  869. }
  870. Effect._baseCache[bufferName] = buffer;
  871. this._engine.bindUniformBufferBase(buffer, bufferName);
  872. };
  873. /**
  874. * Binds block to a uniform.
  875. * @param blockName Name of the block to bind.
  876. * @param index Index to bind.
  877. */
  878. Effect.prototype.bindUniformBlock = function (blockName, index) {
  879. this._engine.bindUniformBlock(this._program, blockName, index);
  880. };
  881. /**
  882. * Sets an interger value on a uniform variable.
  883. * @param uniformName Name of the variable.
  884. * @param value Value to be set.
  885. * @returns this effect.
  886. */
  887. Effect.prototype.setInt = function (uniformName, value) {
  888. var cache = this._valueCache[uniformName];
  889. if (cache !== undefined && cache === value)
  890. return this;
  891. this._valueCache[uniformName] = value;
  892. this._engine.setInt(this.getUniform(uniformName), value);
  893. return this;
  894. };
  895. /**
  896. * Sets an int array on a uniform variable.
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * 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)
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setIntArray2 = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setIntArray2(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * 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)
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setIntArray3 = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setIntArray3(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * 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)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setIntArray4 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setIntArray4(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * Sets an float array on a uniform variable.
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * 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)
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * 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)
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * 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)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * Sets an array on a uniform variable.
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * 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)
  996. * @param uniformName Name of the variable.
  997. * @param array array to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setArray2 = function (uniformName, array) {
  1001. this._valueCache[uniformName] = null;
  1002. this._engine.setArray2(this.getUniform(uniformName), array);
  1003. return this;
  1004. };
  1005. /**
  1006. * 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)
  1007. * @param uniformName Name of the variable.
  1008. * @param array array to be set.
  1009. * @returns this effect.
  1010. */
  1011. Effect.prototype.setArray3 = function (uniformName, array) {
  1012. this._valueCache[uniformName] = null;
  1013. this._engine.setArray3(this.getUniform(uniformName), array);
  1014. return this;
  1015. };
  1016. /**
  1017. * 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)
  1018. * @param uniformName Name of the variable.
  1019. * @param array array to be set.
  1020. * @returns this effect.
  1021. */
  1022. Effect.prototype.setArray4 = function (uniformName, array) {
  1023. this._valueCache[uniformName] = null;
  1024. this._engine.setArray4(this.getUniform(uniformName), array);
  1025. return this;
  1026. };
  1027. /**
  1028. * Sets matrices on a uniform variable.
  1029. * @param uniformName Name of the variable.
  1030. * @param matrices matrices to be set.
  1031. * @returns this effect.
  1032. */
  1033. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1034. if (!matrices) {
  1035. return this;
  1036. }
  1037. this._valueCache[uniformName] = null;
  1038. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1039. return this;
  1040. };
  1041. /**
  1042. * Sets matrix on a uniform variable.
  1043. * @param uniformName Name of the variable.
  1044. * @param matrix matrix to be set.
  1045. * @returns this effect.
  1046. */
  1047. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1048. if (this._cacheMatrix(uniformName, matrix)) {
  1049. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1050. }
  1051. return this;
  1052. };
  1053. /**
  1054. * 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)
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1060. this._valueCache[uniformName] = null;
  1061. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1062. return this;
  1063. };
  1064. /**
  1065. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1066. * @param uniformName Name of the variable.
  1067. * @param matrix matrix to be set.
  1068. * @returns this effect.
  1069. */
  1070. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1071. this._valueCache[uniformName] = null;
  1072. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1073. return this;
  1074. };
  1075. /**
  1076. * Sets a float on a uniform variable.
  1077. * @param uniformName Name of the variable.
  1078. * @param value value to be set.
  1079. * @returns this effect.
  1080. */
  1081. Effect.prototype.setFloat = function (uniformName, value) {
  1082. var cache = this._valueCache[uniformName];
  1083. if (cache !== undefined && cache === value)
  1084. return this;
  1085. this._valueCache[uniformName] = value;
  1086. this._engine.setFloat(this.getUniform(uniformName), value);
  1087. return this;
  1088. };
  1089. /**
  1090. * Sets a boolean on a uniform variable.
  1091. * @param uniformName Name of the variable.
  1092. * @param bool value to be set.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setBool = function (uniformName, bool) {
  1096. var cache = this._valueCache[uniformName];
  1097. if (cache !== undefined && cache === bool)
  1098. return this;
  1099. this._valueCache[uniformName] = bool;
  1100. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a Vector2 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param vector2 vector2 to be set.
  1107. * @returns this effect.
  1108. */
  1109. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1110. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1111. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1112. }
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a float2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param x First float in float2.
  1119. * @param y Second float in float2.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1123. if (this._cacheFloat2(uniformName, x, y)) {
  1124. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1125. }
  1126. return this;
  1127. };
  1128. /**
  1129. * Sets a Vector3 on a uniform variable.
  1130. * @param uniformName Name of the variable.
  1131. * @param vector3 Value to be set.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1135. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1136. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a float3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param x First float in float3.
  1144. * @param y Second float in float3.
  1145. * @param z Third float in float3.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1149. if (this._cacheFloat3(uniformName, x, y, z)) {
  1150. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Vector4 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param vector4 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1161. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a float4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param x First float in float4.
  1170. * @param y Second float in float4.
  1171. * @param z Third float in float4.
  1172. * @param w Fourth float in float4.
  1173. * @returns this effect.
  1174. */
  1175. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1176. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1177. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1178. }
  1179. return this;
  1180. };
  1181. /**
  1182. * Sets a Color3 on a uniform variable.
  1183. * @param uniformName Name of the variable.
  1184. * @param color3 Value to be set.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setColor3 = function (uniformName, color3) {
  1188. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1189. this._engine.setColor3(this.getUniform(uniformName), color3);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color4 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @param alpha Alpha value to be set.
  1198. * @returns this effect.
  1199. */
  1200. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1201. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1202. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1203. }
  1204. return this;
  1205. };
  1206. /**
  1207. * Sets a Color4 on a uniform variable
  1208. * @param uniformName defines the name of the variable
  1209. * @param color4 defines the value to be set
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1213. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1214. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Resets the cache of effects.
  1220. */
  1221. Effect.ResetCache = function () {
  1222. Effect._baseCache = {};
  1223. };
  1224. Effect._uniqueIdSeed = 0;
  1225. Effect._baseCache = {};
  1226. /**
  1227. * Store of each shader (The can be looked up using effect.key)
  1228. */
  1229. Effect.ShadersStore = {};
  1230. /**
  1231. * Store of each included file for a shader (The can be looked up using effect.key)
  1232. */
  1233. Effect.IncludesShadersStore = {};
  1234. return Effect;
  1235. }());
  1236. BABYLON.Effect = Effect;
  1237. })(BABYLON || (BABYLON = {}));
  1238. //# sourceMappingURL=babylon.effect.js.map
  1239. //# sourceMappingURL=babylon.types.js.map
  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. var BABYLON;
  1289. (function (BABYLON) {
  1290. var PointerEventTypes = /** @class */ (function () {
  1291. function PointerEventTypes() {
  1292. }
  1293. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1294. get: function () {
  1295. return PointerEventTypes._POINTERDOWN;
  1296. },
  1297. enumerable: true,
  1298. configurable: true
  1299. });
  1300. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1301. get: function () {
  1302. return PointerEventTypes._POINTERUP;
  1303. },
  1304. enumerable: true,
  1305. configurable: true
  1306. });
  1307. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1308. get: function () {
  1309. return PointerEventTypes._POINTERMOVE;
  1310. },
  1311. enumerable: true,
  1312. configurable: true
  1313. });
  1314. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1315. get: function () {
  1316. return PointerEventTypes._POINTERWHEEL;
  1317. },
  1318. enumerable: true,
  1319. configurable: true
  1320. });
  1321. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1322. get: function () {
  1323. return PointerEventTypes._POINTERPICK;
  1324. },
  1325. enumerable: true,
  1326. configurable: true
  1327. });
  1328. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1329. get: function () {
  1330. return PointerEventTypes._POINTERTAP;
  1331. },
  1332. enumerable: true,
  1333. configurable: true
  1334. });
  1335. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1336. get: function () {
  1337. return PointerEventTypes._POINTERDOUBLETAP;
  1338. },
  1339. enumerable: true,
  1340. configurable: true
  1341. });
  1342. PointerEventTypes._POINTERDOWN = 0x01;
  1343. PointerEventTypes._POINTERUP = 0x02;
  1344. PointerEventTypes._POINTERMOVE = 0x04;
  1345. PointerEventTypes._POINTERWHEEL = 0x08;
  1346. PointerEventTypes._POINTERPICK = 0x10;
  1347. PointerEventTypes._POINTERTAP = 0x20;
  1348. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1349. return PointerEventTypes;
  1350. }());
  1351. BABYLON.PointerEventTypes = PointerEventTypes;
  1352. var PointerInfoBase = /** @class */ (function () {
  1353. function PointerInfoBase(type, event) {
  1354. this.type = type;
  1355. this.event = event;
  1356. }
  1357. return PointerInfoBase;
  1358. }());
  1359. BABYLON.PointerInfoBase = PointerInfoBase;
  1360. /**
  1361. * This class is used to store pointer related info for the onPrePointerObservable event.
  1362. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1363. */
  1364. var PointerInfoPre = /** @class */ (function (_super) {
  1365. __extends(PointerInfoPre, _super);
  1366. function PointerInfoPre(type, event, localX, localY) {
  1367. var _this = _super.call(this, type, event) || this;
  1368. _this.skipOnPointerObservable = false;
  1369. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1370. return _this;
  1371. }
  1372. return PointerInfoPre;
  1373. }(PointerInfoBase));
  1374. BABYLON.PointerInfoPre = PointerInfoPre;
  1375. /**
  1376. * This type contains all the data related to a pointer event in Babylon.js.
  1377. * 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.
  1378. */
  1379. var PointerInfo = /** @class */ (function (_super) {
  1380. __extends(PointerInfo, _super);
  1381. function PointerInfo(type, event, pickInfo) {
  1382. var _this = _super.call(this, type, event) || this;
  1383. _this.pickInfo = pickInfo;
  1384. return _this;
  1385. }
  1386. return PointerInfo;
  1387. }(PointerInfoBase));
  1388. BABYLON.PointerInfo = PointerInfo;
  1389. })(BABYLON || (BABYLON = {}));
  1390. //# sourceMappingURL=babylon.pointerEvents.js.map
  1391. var BABYLON;
  1392. (function (BABYLON) {
  1393. BABYLON.ToGammaSpace = 1 / 2.2;
  1394. BABYLON.ToLinearSpace = 2.2;
  1395. BABYLON.Epsilon = 0.001;
  1396. /**
  1397. * Class used to hold a RBG color
  1398. */
  1399. var Color3 = /** @class */ (function () {
  1400. /**
  1401. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1402. * @param r defines the red component (between 0 and 1, default is 0)
  1403. * @param g defines the green component (between 0 and 1, default is 0)
  1404. * @param b defines the blue component (between 0 and 1, default is 0)
  1405. */
  1406. function Color3(
  1407. /**
  1408. * Defines the red component (between 0 and 1, default is 0)
  1409. */
  1410. r,
  1411. /**
  1412. * Defines the green component (between 0 and 1, default is 0)
  1413. */
  1414. g,
  1415. /**
  1416. * Defines the blue component (between 0 and 1, default is 0)
  1417. */
  1418. b) {
  1419. if (r === void 0) { r = 0; }
  1420. if (g === void 0) { g = 0; }
  1421. if (b === void 0) { b = 0; }
  1422. this.r = r;
  1423. this.g = g;
  1424. this.b = b;
  1425. }
  1426. /**
  1427. * Creates a string with the Color3 current values
  1428. * @returns the string representation of the Color3 object
  1429. */
  1430. Color3.prototype.toString = function () {
  1431. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1432. };
  1433. /**
  1434. * Returns the string "Color3"
  1435. * @returns "Color3"
  1436. */
  1437. Color3.prototype.getClassName = function () {
  1438. return "Color3";
  1439. };
  1440. /**
  1441. * Compute the Color3 hash code
  1442. * @returns an unique number that can be used to hash Color3 objects
  1443. */
  1444. Color3.prototype.getHashCode = function () {
  1445. var hash = this.r || 0;
  1446. hash = (hash * 397) ^ (this.g || 0);
  1447. hash = (hash * 397) ^ (this.b || 0);
  1448. return hash;
  1449. };
  1450. // Operators
  1451. /**
  1452. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1453. * @param array defines the array where to store the r,g,b components
  1454. * @param index defines an optional index in the target array to define where to start storing values
  1455. * @returns the current Color3 object
  1456. */
  1457. Color3.prototype.toArray = function (array, index) {
  1458. if (index === undefined) {
  1459. index = 0;
  1460. }
  1461. array[index] = this.r;
  1462. array[index + 1] = this.g;
  1463. array[index + 2] = this.b;
  1464. return this;
  1465. };
  1466. /**
  1467. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1468. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1469. * @returns a new {BABYLON.Color4} object
  1470. */
  1471. Color3.prototype.toColor4 = function (alpha) {
  1472. if (alpha === void 0) { alpha = 1; }
  1473. return new Color4(this.r, this.g, this.b, alpha);
  1474. };
  1475. /**
  1476. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1477. * @returns the new array
  1478. */
  1479. Color3.prototype.asArray = function () {
  1480. var result = new Array();
  1481. this.toArray(result, 0);
  1482. return result;
  1483. };
  1484. /**
  1485. * Returns the luminance value
  1486. * @returns a float value
  1487. */
  1488. Color3.prototype.toLuminance = function () {
  1489. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1490. };
  1491. /**
  1492. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1493. * @param otherColor defines the second operand
  1494. * @returns the new Color3 object
  1495. */
  1496. Color3.prototype.multiply = function (otherColor) {
  1497. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1498. };
  1499. /**
  1500. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1501. * @param otherColor defines the second operand
  1502. * @param result defines the Color3 object where to store the result
  1503. * @returns the current Color3
  1504. */
  1505. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1506. result.r = this.r * otherColor.r;
  1507. result.g = this.g * otherColor.g;
  1508. result.b = this.b * otherColor.b;
  1509. return this;
  1510. };
  1511. /**
  1512. * Determines equality between Color3 objects
  1513. * @param otherColor defines the second operand
  1514. * @returns true if the rgb values are equal to the given ones
  1515. */
  1516. Color3.prototype.equals = function (otherColor) {
  1517. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1518. };
  1519. /**
  1520. * Determines equality between the current Color3 object and a set of r,b,g values
  1521. * @param r defines the red component to check
  1522. * @param g defines the green component to check
  1523. * @param b defines the blue component to check
  1524. * @returns true if the rgb values are equal to the given ones
  1525. */
  1526. Color3.prototype.equalsFloats = function (r, g, b) {
  1527. return this.r === r && this.g === g && this.b === b;
  1528. };
  1529. /**
  1530. * Multiplies in place each rgb value by scale
  1531. * @param scale defines the scaling factor
  1532. * @returns the updated Color3
  1533. */
  1534. Color3.prototype.scale = function (scale) {
  1535. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1536. };
  1537. /**
  1538. * Multiplies the rgb values by scale and stores the result into "result"
  1539. * @param scale defines the scaling factor
  1540. * @param result defines the Color3 object where to store the result
  1541. * @returns the unmodified current Color3
  1542. */
  1543. Color3.prototype.scaleToRef = function (scale, result) {
  1544. result.r = this.r * scale;
  1545. result.g = this.g * scale;
  1546. result.b = this.b * scale;
  1547. return this;
  1548. };
  1549. /**
  1550. * Scale the current Color3 values by a factor and add the result to a given Color3
  1551. * @param scale defines the scale factor
  1552. * @param result defines color to store the result into
  1553. * @returns the unmodified current Color3
  1554. */
  1555. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1556. result.r += this.r * scale;
  1557. result.g += this.g * scale;
  1558. result.b += this.b * scale;
  1559. return this;
  1560. };
  1561. /**
  1562. * Clamps the rgb values by the min and max values and stores the result into "result"
  1563. * @param min defines minimum clamping value (default is 0)
  1564. * @param max defines maximum clamping value (default is 1)
  1565. * @param result defines color to store the result into
  1566. * @returns the original Color3
  1567. */
  1568. Color3.prototype.clampToRef = function (min, max, result) {
  1569. if (min === void 0) { min = 0; }
  1570. if (max === void 0) { max = 1; }
  1571. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1572. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1573. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1574. return this;
  1575. };
  1576. /**
  1577. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1578. * @param otherColor defines the second operand
  1579. * @returns the new Color3
  1580. */
  1581. Color3.prototype.add = function (otherColor) {
  1582. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1583. };
  1584. /**
  1585. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1586. * @param otherColor defines the second operand
  1587. * @param result defines Color3 object to store the result into
  1588. * @returns the unmodified current Color3
  1589. */
  1590. Color3.prototype.addToRef = function (otherColor, result) {
  1591. result.r = this.r + otherColor.r;
  1592. result.g = this.g + otherColor.g;
  1593. result.b = this.b + otherColor.b;
  1594. return this;
  1595. };
  1596. /**
  1597. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1598. * @param otherColor defines the second operand
  1599. * @returns the new Color3
  1600. */
  1601. Color3.prototype.subtract = function (otherColor) {
  1602. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1603. };
  1604. /**
  1605. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1606. * @param otherColor defines the second operand
  1607. * @param result defines Color3 object to store the result into
  1608. * @returns the unmodified current Color3
  1609. */
  1610. Color3.prototype.subtractToRef = function (otherColor, result) {
  1611. result.r = this.r - otherColor.r;
  1612. result.g = this.g - otherColor.g;
  1613. result.b = this.b - otherColor.b;
  1614. return this;
  1615. };
  1616. /**
  1617. * Copy the current object
  1618. * @returns a new Color3 copied the current one
  1619. */
  1620. Color3.prototype.clone = function () {
  1621. return new Color3(this.r, this.g, this.b);
  1622. };
  1623. /**
  1624. * Copies the rgb values from the source in the current Color3
  1625. * @param source defines the source Color3 object
  1626. * @returns the updated Color3 object
  1627. */
  1628. Color3.prototype.copyFrom = function (source) {
  1629. this.r = source.r;
  1630. this.g = source.g;
  1631. this.b = source.b;
  1632. return this;
  1633. };
  1634. /**
  1635. * Updates the Color3 rgb values from the given floats
  1636. * @param r defines the red component to read from
  1637. * @param g defines the green component to read from
  1638. * @param b defines the blue component to read from
  1639. * @returns the current Color3 object
  1640. */
  1641. Color3.prototype.copyFromFloats = function (r, g, b) {
  1642. this.r = r;
  1643. this.g = g;
  1644. this.b = b;
  1645. return this;
  1646. };
  1647. /**
  1648. * Updates the Color3 rgb values from the given floats
  1649. * @param r defines the red component to read from
  1650. * @param g defines the green component to read from
  1651. * @param b defines the blue component to read from
  1652. * @returns the current Color3 object
  1653. */
  1654. Color3.prototype.set = function (r, g, b) {
  1655. return this.copyFromFloats(r, g, b);
  1656. };
  1657. /**
  1658. * Compute the Color3 hexadecimal code as a string
  1659. * @returns a string containing the hexadecimal representation of the Color3 object
  1660. */
  1661. Color3.prototype.toHexString = function () {
  1662. var intR = (this.r * 255) | 0;
  1663. var intG = (this.g * 255) | 0;
  1664. var intB = (this.b * 255) | 0;
  1665. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1666. };
  1667. /**
  1668. * Computes a new Color3 converted from the current one to linear space
  1669. * @returns a new Color3 object
  1670. */
  1671. Color3.prototype.toLinearSpace = function () {
  1672. var convertedColor = new Color3();
  1673. this.toLinearSpaceToRef(convertedColor);
  1674. return convertedColor;
  1675. };
  1676. /**
  1677. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1678. * @param convertedColor defines the Color3 object where to store the linear space version
  1679. * @returns the unmodified Color3
  1680. */
  1681. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1682. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1683. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1684. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1685. return this;
  1686. };
  1687. /**
  1688. * Computes a new Color3 converted from the current one to gamma space
  1689. * @returns a new Color3 object
  1690. */
  1691. Color3.prototype.toGammaSpace = function () {
  1692. var convertedColor = new Color3();
  1693. this.toGammaSpaceToRef(convertedColor);
  1694. return convertedColor;
  1695. };
  1696. /**
  1697. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1698. * @param convertedColor defines the Color3 object where to store the gamma space version
  1699. * @returns the unmodified Color3
  1700. */
  1701. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1702. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1703. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1704. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1705. return this;
  1706. };
  1707. // Statics
  1708. /**
  1709. * Creates a new Color3 from the string containing valid hexadecimal values
  1710. * @param hex defines a string containing valid hexadecimal values
  1711. * @returns a new Color3 object
  1712. */
  1713. Color3.FromHexString = function (hex) {
  1714. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1715. return new Color3(0, 0, 0);
  1716. }
  1717. var r = parseInt(hex.substring(1, 3), 16);
  1718. var g = parseInt(hex.substring(3, 5), 16);
  1719. var b = parseInt(hex.substring(5, 7), 16);
  1720. return Color3.FromInts(r, g, b);
  1721. };
  1722. /**
  1723. * Creates a new Vector3 from the starting index of the given array
  1724. * @param array defines the source array
  1725. * @param offset defines an offset in the source array
  1726. * @returns a new Color3 object
  1727. */
  1728. Color3.FromArray = function (array, offset) {
  1729. if (offset === void 0) { offset = 0; }
  1730. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1731. };
  1732. /**
  1733. * Creates a new Color3 from integer values (< 256)
  1734. * @param r defines the red component to read from (value between 0 and 255)
  1735. * @param g defines the green component to read from (value between 0 and 255)
  1736. * @param b defines the blue component to read from (value between 0 and 255)
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.FromInts = function (r, g, b) {
  1740. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1741. };
  1742. /**
  1743. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1744. * @param start defines the start Color3 value
  1745. * @param end defines the end Color3 value
  1746. * @param amount defines the gradient value between start and end
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Lerp = function (start, end, amount) {
  1750. var r = start.r + ((end.r - start.r) * amount);
  1751. var g = start.g + ((end.g - start.g) * amount);
  1752. var b = start.b + ((end.b - start.b) * amount);
  1753. return new Color3(r, g, b);
  1754. };
  1755. /**
  1756. * Returns a Color3 value containing a red color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Red = function () { return new Color3(1, 0, 0); };
  1760. /**
  1761. * Returns a Color3 value containing a green color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Green = function () { return new Color3(0, 1, 0); };
  1765. /**
  1766. * Returns a Color3 value containing a blue color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1770. /**
  1771. * Returns a Color3 value containing a black color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Black = function () { return new Color3(0, 0, 0); };
  1775. /**
  1776. * Returns a Color3 value containing a white color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.White = function () { return new Color3(1, 1, 1); };
  1780. /**
  1781. * Returns a Color3 value containing a purple color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1785. /**
  1786. * Returns a Color3 value containing a magenta color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1790. /**
  1791. * Returns a Color3 value containing a yellow color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1795. /**
  1796. * Returns a Color3 value containing a gray color
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1800. /**
  1801. * Returns a Color3 value containing a teal color
  1802. * @returns a new Color3 object
  1803. */
  1804. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1805. /**
  1806. * Returns a Color3 value containing a random color
  1807. * @returns a new Color3 object
  1808. */
  1809. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1810. return Color3;
  1811. }());
  1812. BABYLON.Color3 = Color3;
  1813. /**
  1814. * Class used to hold a RBGA color
  1815. */
  1816. var Color4 = /** @class */ (function () {
  1817. /**
  1818. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1819. * @param r defines the red component (between 0 and 1, default is 0)
  1820. * @param g defines the green component (between 0 and 1, default is 0)
  1821. * @param b defines the blue component (between 0 and 1, default is 0)
  1822. * @param a defines the alpha component (between 0 and 1, default is 1)
  1823. */
  1824. function Color4(
  1825. /**
  1826. * Defines the red component (between 0 and 1, default is 0)
  1827. */
  1828. r,
  1829. /**
  1830. * Defines the green component (between 0 and 1, default is 0)
  1831. */
  1832. g,
  1833. /**
  1834. * Defines the blue component (between 0 and 1, default is 0)
  1835. */
  1836. b,
  1837. /**
  1838. * Defines the alpha component (between 0 and 1, default is 1)
  1839. */
  1840. a) {
  1841. if (r === void 0) { r = 0; }
  1842. if (g === void 0) { g = 0; }
  1843. if (b === void 0) { b = 0; }
  1844. if (a === void 0) { a = 1; }
  1845. this.r = r;
  1846. this.g = g;
  1847. this.b = b;
  1848. this.a = a;
  1849. }
  1850. // Operators
  1851. /**
  1852. * Adds in place the given Color4 values to the current Color4 object
  1853. * @param right defines the second operand
  1854. * @returns the current updated Color4 object
  1855. */
  1856. Color4.prototype.addInPlace = function (right) {
  1857. this.r += right.r;
  1858. this.g += right.g;
  1859. this.b += right.b;
  1860. this.a += right.a;
  1861. return this;
  1862. };
  1863. /**
  1864. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1865. * @returns the new array
  1866. */
  1867. Color4.prototype.asArray = function () {
  1868. var result = new Array();
  1869. this.toArray(result, 0);
  1870. return result;
  1871. };
  1872. /**
  1873. * Stores from the starting index in the given array the Color4 successive values
  1874. * @param array defines the array where to store the r,g,b components
  1875. * @param index defines an optional index in the target array to define where to start storing values
  1876. * @returns the current Color4 object
  1877. */
  1878. Color4.prototype.toArray = function (array, index) {
  1879. if (index === undefined) {
  1880. index = 0;
  1881. }
  1882. array[index] = this.r;
  1883. array[index + 1] = this.g;
  1884. array[index + 2] = this.b;
  1885. array[index + 3] = this.a;
  1886. return this;
  1887. };
  1888. /**
  1889. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1890. * @param right defines the second operand
  1891. * @returns a new Color4 object
  1892. */
  1893. Color4.prototype.add = function (right) {
  1894. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1895. };
  1896. /**
  1897. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1898. * @param right defines the second operand
  1899. * @returns a new Color4 object
  1900. */
  1901. Color4.prototype.subtract = function (right) {
  1902. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1903. };
  1904. /**
  1905. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1906. * @param right defines the second operand
  1907. * @param result defines the Color4 object where to store the result
  1908. * @returns the current Color4 object
  1909. */
  1910. Color4.prototype.subtractToRef = function (right, result) {
  1911. result.r = this.r - right.r;
  1912. result.g = this.g - right.g;
  1913. result.b = this.b - right.b;
  1914. result.a = this.a - right.a;
  1915. return this;
  1916. };
  1917. /**
  1918. * Creates a new Color4 with the current Color4 values multiplied by scale
  1919. * @param scale defines the scaling factor to apply
  1920. * @returns a new Color4 object
  1921. */
  1922. Color4.prototype.scale = function (scale) {
  1923. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1924. };
  1925. /**
  1926. * Multiplies the current Color4 values by scale and stores the result in "result"
  1927. * @param scale defines the scaling factor to apply
  1928. * @param result defines the Color4 object where to store the result
  1929. * @returns the current unmodified Color4
  1930. */
  1931. Color4.prototype.scaleToRef = function (scale, result) {
  1932. result.r = this.r * scale;
  1933. result.g = this.g * scale;
  1934. result.b = this.b * scale;
  1935. result.a = this.a * scale;
  1936. return this;
  1937. };
  1938. /**
  1939. * Scale the current Color4 values by a factor and add the result to a given Color4
  1940. * @param scale defines the scale factor
  1941. * @param result defines the Color4 object where to store the result
  1942. * @returns the unmodified current Color4
  1943. */
  1944. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1945. result.r += this.r * scale;
  1946. result.g += this.g * scale;
  1947. result.b += this.b * scale;
  1948. result.a += this.a * scale;
  1949. return this;
  1950. };
  1951. /**
  1952. * Clamps the rgb values by the min and max values and stores the result into "result"
  1953. * @param min defines minimum clamping value (default is 0)
  1954. * @param max defines maximum clamping value (default is 1)
  1955. * @param result defines color to store the result into.
  1956. * @returns the cuurent Color4
  1957. */
  1958. Color4.prototype.clampToRef = function (min, max, result) {
  1959. if (min === void 0) { min = 0; }
  1960. if (max === void 0) { max = 1; }
  1961. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1962. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1963. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1964. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1965. return this;
  1966. };
  1967. /**
  1968. * Multipy an Color4 value by another and return a new Color4 object
  1969. * @param color defines the Color4 value to multiply by
  1970. * @returns a new Color4 object
  1971. */
  1972. Color4.prototype.multiply = function (color) {
  1973. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1974. };
  1975. /**
  1976. * Multipy a Color4 value by another and push the result in a reference value
  1977. * @param color defines the Color4 value to multiply by
  1978. * @param result defines the Color4 to fill the result in
  1979. * @returns the result Color4
  1980. */
  1981. Color4.prototype.multiplyToRef = function (color, result) {
  1982. result.r = this.r * color.r;
  1983. result.g = this.g * color.g;
  1984. result.b = this.b * color.b;
  1985. result.a = this.a * color.a;
  1986. return result;
  1987. };
  1988. /**
  1989. * Creates a string with the Color4 current values
  1990. * @returns the string representation of the Color4 object
  1991. */
  1992. Color4.prototype.toString = function () {
  1993. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1994. };
  1995. /**
  1996. * Returns the string "Color4"
  1997. * @returns "Color4"
  1998. */
  1999. Color4.prototype.getClassName = function () {
  2000. return "Color4";
  2001. };
  2002. /**
  2003. * Compute the Color4 hash code
  2004. * @returns an unique number that can be used to hash Color4 objects
  2005. */
  2006. Color4.prototype.getHashCode = function () {
  2007. var hash = this.r || 0;
  2008. hash = (hash * 397) ^ (this.g || 0);
  2009. hash = (hash * 397) ^ (this.b || 0);
  2010. hash = (hash * 397) ^ (this.a || 0);
  2011. return hash;
  2012. };
  2013. /**
  2014. * Creates a new Color4 copied from the current one
  2015. * @returns a new Color4 object
  2016. */
  2017. Color4.prototype.clone = function () {
  2018. return new Color4(this.r, this.g, this.b, this.a);
  2019. };
  2020. /**
  2021. * Copies the given Color4 values into the current one
  2022. * @param source defines the source Color4 object
  2023. * @returns the current updated Color4 object
  2024. */
  2025. Color4.prototype.copyFrom = function (source) {
  2026. this.r = source.r;
  2027. this.g = source.g;
  2028. this.b = source.b;
  2029. this.a = source.a;
  2030. return this;
  2031. };
  2032. /**
  2033. * Copies the given float values into the current one
  2034. * @param r defines the red component to read from
  2035. * @param g defines the green component to read from
  2036. * @param b defines the blue component to read from
  2037. * @param a defines the alpha component to read from
  2038. * @returns the current updated Color4 object
  2039. */
  2040. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2041. this.r = r;
  2042. this.g = g;
  2043. this.b = b;
  2044. this.a = a;
  2045. return this;
  2046. };
  2047. /**
  2048. * Copies the given float values into the current one
  2049. * @param r defines the red component to read from
  2050. * @param g defines the green component to read from
  2051. * @param b defines the blue component to read from
  2052. * @param a defines the alpha component to read from
  2053. * @returns the current updated Color4 object
  2054. */
  2055. Color4.prototype.set = function (r, g, b, a) {
  2056. return this.copyFromFloats(r, g, b, a);
  2057. };
  2058. /**
  2059. * Compute the Color4 hexadecimal code as a string
  2060. * @returns a string containing the hexadecimal representation of the Color4 object
  2061. */
  2062. Color4.prototype.toHexString = function () {
  2063. var intR = (this.r * 255) | 0;
  2064. var intG = (this.g * 255) | 0;
  2065. var intB = (this.b * 255) | 0;
  2066. var intA = (this.a * 255) | 0;
  2067. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2068. };
  2069. /**
  2070. * Computes a new Color4 converted from the current one to linear space
  2071. * @returns a new Color4 object
  2072. */
  2073. Color4.prototype.toLinearSpace = function () {
  2074. var convertedColor = new Color4();
  2075. this.toLinearSpaceToRef(convertedColor);
  2076. return convertedColor;
  2077. };
  2078. /**
  2079. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2080. * @param convertedColor defines the Color4 object where to store the linear space version
  2081. * @returns the unmodified Color4
  2082. */
  2083. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2084. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2085. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2086. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2087. convertedColor.a = this.a;
  2088. return this;
  2089. };
  2090. /**
  2091. * Computes a new Color4 converted from the current one to gamma space
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.prototype.toGammaSpace = function () {
  2095. var convertedColor = new Color4();
  2096. this.toGammaSpaceToRef(convertedColor);
  2097. return convertedColor;
  2098. };
  2099. /**
  2100. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2101. * @param convertedColor defines the Color4 object where to store the gamma space version
  2102. * @returns the unmodified Color4
  2103. */
  2104. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2105. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2106. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2107. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2108. convertedColor.a = this.a;
  2109. return this;
  2110. };
  2111. // Statics
  2112. /**
  2113. * Creates a new Color4 from the string containing valid hexadecimal values
  2114. * @param hex defines a string containing valid hexadecimal values
  2115. * @returns a new Color4 object
  2116. */
  2117. Color4.FromHexString = function (hex) {
  2118. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2119. return new Color4(0.0, 0.0, 0.0, 0.0);
  2120. }
  2121. var r = parseInt(hex.substring(1, 3), 16);
  2122. var g = parseInt(hex.substring(3, 5), 16);
  2123. var b = parseInt(hex.substring(5, 7), 16);
  2124. var a = parseInt(hex.substring(7, 9), 16);
  2125. return Color4.FromInts(r, g, b, a);
  2126. };
  2127. /**
  2128. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2129. * @param left defines the start value
  2130. * @param right defines the end value
  2131. * @param amount defines the gradient factor
  2132. * @returns a new Color4 object
  2133. */
  2134. Color4.Lerp = function (left, right, amount) {
  2135. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2136. Color4.LerpToRef(left, right, amount, result);
  2137. return result;
  2138. };
  2139. /**
  2140. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2141. * @param left defines the start value
  2142. * @param right defines the end value
  2143. * @param amount defines the gradient factor
  2144. * @param result defines the Color4 object where to store data
  2145. */
  2146. Color4.LerpToRef = function (left, right, amount, result) {
  2147. result.r = left.r + (right.r - left.r) * amount;
  2148. result.g = left.g + (right.g - left.g) * amount;
  2149. result.b = left.b + (right.b - left.b) * amount;
  2150. result.a = left.a + (right.a - left.a) * amount;
  2151. };
  2152. /**
  2153. * Creates a new Color4 from the starting index element of the given array
  2154. * @param array defines the source array to read from
  2155. * @param offset defines the offset in the source array
  2156. * @returns a new Color4 object
  2157. */
  2158. Color4.FromArray = function (array, offset) {
  2159. if (offset === void 0) { offset = 0; }
  2160. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2161. };
  2162. /**
  2163. * Creates a new Color3 from integer values (< 256)
  2164. * @param r defines the red component to read from (value between 0 and 255)
  2165. * @param g defines the green component to read from (value between 0 and 255)
  2166. * @param b defines the blue component to read from (value between 0 and 255)
  2167. * @param a defines the alpha component to read from (value between 0 and 255)
  2168. * @returns a new Color3 object
  2169. */
  2170. Color4.FromInts = function (r, g, b, a) {
  2171. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2172. };
  2173. /**
  2174. * Check the content of a given array and convert it to an array containing RGBA data
  2175. * If the original array was already containing count * 4 values then it is returned directly
  2176. * @param colors defines the array to check
  2177. * @param count defines the number of RGBA data to expect
  2178. * @returns an array containing count * 4 values (RGBA)
  2179. */
  2180. Color4.CheckColors4 = function (colors, count) {
  2181. // Check if color3 was used
  2182. if (colors.length === count * 3) {
  2183. var colors4 = [];
  2184. for (var index = 0; index < colors.length; index += 3) {
  2185. var newIndex = (index / 3) * 4;
  2186. colors4[newIndex] = colors[index];
  2187. colors4[newIndex + 1] = colors[index + 1];
  2188. colors4[newIndex + 2] = colors[index + 2];
  2189. colors4[newIndex + 3] = 1.0;
  2190. }
  2191. return colors4;
  2192. }
  2193. return colors;
  2194. };
  2195. return Color4;
  2196. }());
  2197. BABYLON.Color4 = Color4;
  2198. /**
  2199. * Class representing a vector containing 2 coordinates
  2200. */
  2201. var Vector2 = /** @class */ (function () {
  2202. /**
  2203. * Creates a new Vector2 from the given x and y coordinates
  2204. * @param x defines the first coordinate
  2205. * @param y defines the second coordinate
  2206. */
  2207. function Vector2(
  2208. /** defines the first coordinate */
  2209. x,
  2210. /** defines the second coordinate */
  2211. y) {
  2212. this.x = x;
  2213. this.y = y;
  2214. }
  2215. /**
  2216. * Gets a string with the Vector2 coordinates
  2217. * @returns a string with the Vector2 coordinates
  2218. */
  2219. Vector2.prototype.toString = function () {
  2220. return "{X: " + this.x + " Y:" + this.y + "}";
  2221. };
  2222. /**
  2223. * Gets class name
  2224. * @returns the string "Vector2"
  2225. */
  2226. Vector2.prototype.getClassName = function () {
  2227. return "Vector2";
  2228. };
  2229. /**
  2230. * Gets current vector hash code
  2231. * @returns the Vector2 hash code as a number
  2232. */
  2233. Vector2.prototype.getHashCode = function () {
  2234. var hash = this.x || 0;
  2235. hash = (hash * 397) ^ (this.y || 0);
  2236. return hash;
  2237. };
  2238. // Operators
  2239. /**
  2240. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2241. * @param array defines the source array
  2242. * @param index defines the offset in source array
  2243. * @returns the current Vector2
  2244. */
  2245. Vector2.prototype.toArray = function (array, index) {
  2246. if (index === void 0) { index = 0; }
  2247. array[index] = this.x;
  2248. array[index + 1] = this.y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Copy the current vector to an array
  2253. * @returns a new array with 2 elements: the Vector2 coordinates.
  2254. */
  2255. Vector2.prototype.asArray = function () {
  2256. var result = new Array();
  2257. this.toArray(result, 0);
  2258. return result;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2262. * @param source defines the source Vector2
  2263. * @returns the current updated Vector2
  2264. */
  2265. Vector2.prototype.copyFrom = function (source) {
  2266. this.x = source.x;
  2267. this.y = source.y;
  2268. return this;
  2269. };
  2270. /**
  2271. * Sets the Vector2 coordinates with the given floats
  2272. * @param x defines the first coordinate
  2273. * @param y defines the second coordinate
  2274. * @returns the current updated Vector2
  2275. */
  2276. Vector2.prototype.copyFromFloats = function (x, y) {
  2277. this.x = x;
  2278. this.y = y;
  2279. return this;
  2280. };
  2281. /**
  2282. * Sets the Vector2 coordinates with the given floats
  2283. * @param x defines the first coordinate
  2284. * @param y defines the second coordinate
  2285. * @returns the current updated Vector2
  2286. */
  2287. Vector2.prototype.set = function (x, y) {
  2288. return this.copyFromFloats(x, y);
  2289. };
  2290. /**
  2291. * Add another vector with the current one
  2292. * @param otherVector defines the other vector
  2293. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2294. */
  2295. Vector2.prototype.add = function (otherVector) {
  2296. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2297. };
  2298. /**
  2299. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2300. * @param otherVector defines the other vector
  2301. * @param result defines the target vector
  2302. * @returns the unmodified current Vector2
  2303. */
  2304. Vector2.prototype.addToRef = function (otherVector, result) {
  2305. result.x = this.x + otherVector.x;
  2306. result.y = this.y + otherVector.y;
  2307. return this;
  2308. };
  2309. /**
  2310. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2311. * @param otherVector defines the other vector
  2312. * @returns the current updated Vector2
  2313. */
  2314. Vector2.prototype.addInPlace = function (otherVector) {
  2315. this.x += otherVector.x;
  2316. this.y += otherVector.y;
  2317. return this;
  2318. };
  2319. /**
  2320. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2321. * @param otherVector defines the other vector
  2322. * @returns a new Vector2
  2323. */
  2324. Vector2.prototype.addVector3 = function (otherVector) {
  2325. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2326. };
  2327. /**
  2328. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2329. * @param otherVector defines the other vector
  2330. * @returns a new Vector2
  2331. */
  2332. Vector2.prototype.subtract = function (otherVector) {
  2333. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2334. };
  2335. /**
  2336. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2337. * @param otherVector defines the other vector
  2338. * @param result defines the target vector
  2339. * @returns the unmodified current Vector2
  2340. */
  2341. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2342. result.x = this.x - otherVector.x;
  2343. result.y = this.y - otherVector.y;
  2344. return this;
  2345. };
  2346. /**
  2347. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2348. * @param otherVector defines the other vector
  2349. * @returns the current updated Vector2
  2350. */
  2351. Vector2.prototype.subtractInPlace = function (otherVector) {
  2352. this.x -= otherVector.x;
  2353. this.y -= otherVector.y;
  2354. return this;
  2355. };
  2356. /**
  2357. * Multiplies in place the current Vector2 coordinates by the given ones
  2358. * @param otherVector defines the other vector
  2359. * @returns the current updated Vector2
  2360. */
  2361. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2362. this.x *= otherVector.x;
  2363. this.y *= otherVector.y;
  2364. return this;
  2365. };
  2366. /**
  2367. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2368. * @param otherVector defines the other vector
  2369. * @returns a new Vector2
  2370. */
  2371. Vector2.prototype.multiply = function (otherVector) {
  2372. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2373. };
  2374. /**
  2375. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2376. * @param otherVector defines the other vector
  2377. * @param result defines the target vector
  2378. * @returns the unmodified current Vector2
  2379. */
  2380. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2381. result.x = this.x * otherVector.x;
  2382. result.y = this.y * otherVector.y;
  2383. return this;
  2384. };
  2385. /**
  2386. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2387. * @param x defines the first coordinate
  2388. * @param y defines the second coordinate
  2389. * @returns a new Vector2
  2390. */
  2391. Vector2.prototype.multiplyByFloats = function (x, y) {
  2392. return new Vector2(this.x * x, this.y * y);
  2393. };
  2394. /**
  2395. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2396. * @param otherVector defines the other vector
  2397. * @returns a new Vector2
  2398. */
  2399. Vector2.prototype.divide = function (otherVector) {
  2400. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2401. };
  2402. /**
  2403. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2404. * @param otherVector defines the other vector
  2405. * @param result defines the target vector
  2406. * @returns the unmodified current Vector2
  2407. */
  2408. Vector2.prototype.divideToRef = function (otherVector, result) {
  2409. result.x = this.x / otherVector.x;
  2410. result.y = this.y / otherVector.y;
  2411. return this;
  2412. };
  2413. /**
  2414. * Divides the current Vector3 coordinates by the given ones
  2415. * @param otherVector defines the other vector
  2416. * @returns the current updated Vector2
  2417. */
  2418. Vector2.prototype.divideInPlace = function (otherVector) {
  2419. return this.divideToRef(otherVector, this);
  2420. };
  2421. /**
  2422. * Gets a new Vector2 with current Vector2 negated coordinates
  2423. * @returns a new Vector2
  2424. */
  2425. Vector2.prototype.negate = function () {
  2426. return new Vector2(-this.x, -this.y);
  2427. };
  2428. /**
  2429. * Multiply the Vector2 coordinates by scale
  2430. * @param scale defines the scaling factor
  2431. * @returns the current updated Vector2
  2432. */
  2433. Vector2.prototype.scaleInPlace = function (scale) {
  2434. this.x *= scale;
  2435. this.y *= scale;
  2436. return this;
  2437. };
  2438. /**
  2439. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2440. * @param scale defines the scaling factor
  2441. * @returns a new Vector2
  2442. */
  2443. Vector2.prototype.scale = function (scale) {
  2444. var result = new Vector2(0, 0);
  2445. this.scaleToRef(scale, result);
  2446. return result;
  2447. };
  2448. /**
  2449. * Scale the current Vector2 values by a factor to a given Vector2
  2450. * @param scale defines the scale factor
  2451. * @param result defines the Vector2 object where to store the result
  2452. * @returns the unmodified current Vector2
  2453. */
  2454. Vector2.prototype.scaleToRef = function (scale, result) {
  2455. result.x = this.x * scale;
  2456. result.y = this.y * scale;
  2457. return this;
  2458. };
  2459. /**
  2460. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2461. * @param scale defines the scale factor
  2462. * @param result defines the Vector2 object where to store the result
  2463. * @returns the unmodified current Vector2
  2464. */
  2465. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2466. result.x += this.x * scale;
  2467. result.y += this.y * scale;
  2468. return this;
  2469. };
  2470. /**
  2471. * Gets a boolean if two vectors are equals
  2472. * @param otherVector defines the other vector
  2473. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2474. */
  2475. Vector2.prototype.equals = function (otherVector) {
  2476. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2477. };
  2478. /**
  2479. * Gets a boolean if two vectors are equals (using an epsilon value)
  2480. * @param otherVector defines the other vector
  2481. * @param epsilon defines the minimal distance to consider equality
  2482. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2483. */
  2484. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2485. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2486. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2487. };
  2488. // Properties
  2489. /**
  2490. * Gets the length of the vector
  2491. * @returns the vector length (float)
  2492. */
  2493. Vector2.prototype.length = function () {
  2494. return Math.sqrt(this.x * this.x + this.y * this.y);
  2495. };
  2496. /**
  2497. * Gets the vector squared length
  2498. * @returns the vector squared length (float)
  2499. */
  2500. Vector2.prototype.lengthSquared = function () {
  2501. return (this.x * this.x + this.y * this.y);
  2502. };
  2503. // Methods
  2504. /**
  2505. * Normalize the vector
  2506. * @returns the current updated Vector2
  2507. */
  2508. Vector2.prototype.normalize = function () {
  2509. var len = this.length();
  2510. if (len === 0)
  2511. return this;
  2512. var num = 1.0 / len;
  2513. this.x *= num;
  2514. this.y *= num;
  2515. return this;
  2516. };
  2517. /**
  2518. * Gets a new Vector2 copied from the Vector2
  2519. * @returns a new Vector2
  2520. */
  2521. Vector2.prototype.clone = function () {
  2522. return new Vector2(this.x, this.y);
  2523. };
  2524. // Statics
  2525. /**
  2526. * Gets a new Vector2(0, 0)
  2527. * @returns a new Vector2
  2528. */
  2529. Vector2.Zero = function () {
  2530. return new Vector2(0, 0);
  2531. };
  2532. /**
  2533. * Gets a new Vector2(1, 1)
  2534. * @returns a new Vector2
  2535. */
  2536. Vector2.One = function () {
  2537. return new Vector2(1, 1);
  2538. };
  2539. /**
  2540. * Gets a new Vector2 set from the given index element of the given array
  2541. * @param array defines the data source
  2542. * @param offset defines the offset in the data source
  2543. * @returns a new Vector2
  2544. */
  2545. Vector2.FromArray = function (array, offset) {
  2546. if (offset === void 0) { offset = 0; }
  2547. return new Vector2(array[offset], array[offset + 1]);
  2548. };
  2549. /**
  2550. * Sets "result" from the given index element of the given array
  2551. * @param array defines the data source
  2552. * @param offset defines the offset in the data source
  2553. * @param result defines the target vector
  2554. */
  2555. Vector2.FromArrayToRef = function (array, offset, result) {
  2556. result.x = array[offset];
  2557. result.y = array[offset + 1];
  2558. };
  2559. /**
  2560. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2561. * @param value1 defines 1st point of control
  2562. * @param value2 defines 2nd point of control
  2563. * @param value3 defines 3rd point of control
  2564. * @param value4 defines 4th point of control
  2565. * @param amount defines the interpolation factor
  2566. * @returns a new Vector2
  2567. */
  2568. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2569. var squared = amount * amount;
  2570. var cubed = amount * squared;
  2571. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2572. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2573. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2574. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2575. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2576. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2577. return new Vector2(x, y);
  2578. };
  2579. /**
  2580. * 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".
  2581. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2582. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2583. * @param value defines the value to clamp
  2584. * @param min defines the lower limit
  2585. * @param max defines the upper limit
  2586. * @returns a new Vector2
  2587. */
  2588. Vector2.Clamp = function (value, min, max) {
  2589. var x = value.x;
  2590. x = (x > max.x) ? max.x : x;
  2591. x = (x < min.x) ? min.x : x;
  2592. var y = value.y;
  2593. y = (y > max.y) ? max.y : y;
  2594. y = (y < min.y) ? min.y : y;
  2595. return new Vector2(x, y);
  2596. };
  2597. /**
  2598. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2599. * @param value1 defines the 1st control point
  2600. * @param tangent1 defines the outgoing tangent
  2601. * @param value2 defines the 2nd control point
  2602. * @param tangent2 defines the incoming tangent
  2603. * @param amount defines the interpolation factor
  2604. * @returns a new Vector2
  2605. */
  2606. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2607. var squared = amount * amount;
  2608. var cubed = amount * squared;
  2609. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2610. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2611. var part3 = (cubed - (2.0 * squared)) + amount;
  2612. var part4 = cubed - squared;
  2613. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2614. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2615. return new Vector2(x, y);
  2616. };
  2617. /**
  2618. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2619. * @param start defines the start vector
  2620. * @param end defines the end vector
  2621. * @param amount defines the interpolation factor
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.Lerp = function (start, end, amount) {
  2625. var x = start.x + ((end.x - start.x) * amount);
  2626. var y = start.y + ((end.y - start.y) * amount);
  2627. return new Vector2(x, y);
  2628. };
  2629. /**
  2630. * Gets the dot product of the vector "left" and the vector "right"
  2631. * @param left defines first vector
  2632. * @param right defines second vector
  2633. * @returns the dot product (float)
  2634. */
  2635. Vector2.Dot = function (left, right) {
  2636. return left.x * right.x + left.y * right.y;
  2637. };
  2638. /**
  2639. * Returns a new Vector2 equal to the normalized given vector
  2640. * @param vector defines the vector to normalize
  2641. * @returns a new Vector2
  2642. */
  2643. Vector2.Normalize = function (vector) {
  2644. var newVector = vector.clone();
  2645. newVector.normalize();
  2646. return newVector;
  2647. };
  2648. /**
  2649. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2650. * @param left defines 1st vector
  2651. * @param right defines 2nd vector
  2652. * @returns a new Vector2
  2653. */
  2654. Vector2.Minimize = function (left, right) {
  2655. var x = (left.x < right.x) ? left.x : right.x;
  2656. var y = (left.y < right.y) ? left.y : right.y;
  2657. return new Vector2(x, y);
  2658. };
  2659. /**
  2660. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2661. * @param left defines 1st vector
  2662. * @param right defines 2nd vector
  2663. * @returns a new Vector2
  2664. */
  2665. Vector2.Maximize = function (left, right) {
  2666. var x = (left.x > right.x) ? left.x : right.x;
  2667. var y = (left.y > right.y) ? left.y : right.y;
  2668. return new Vector2(x, y);
  2669. };
  2670. /**
  2671. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2672. * @param vector defines the vector to transform
  2673. * @param transformation defines the matrix to apply
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Transform = function (vector, transformation) {
  2677. var r = Vector2.Zero();
  2678. Vector2.TransformToRef(vector, transformation, r);
  2679. return r;
  2680. };
  2681. /**
  2682. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2683. * @param vector defines the vector to transform
  2684. * @param transformation defines the matrix to apply
  2685. * @param result defines the target vector
  2686. */
  2687. Vector2.TransformToRef = function (vector, transformation, result) {
  2688. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2689. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2690. result.x = x;
  2691. result.y = y;
  2692. };
  2693. /**
  2694. * Determines if a given vector is included in a triangle
  2695. * @param p defines the vector to test
  2696. * @param p0 defines 1st triangle point
  2697. * @param p1 defines 2nd triangle point
  2698. * @param p2 defines 3rd triangle point
  2699. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2700. */
  2701. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2702. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2703. var sign = a < 0 ? -1 : 1;
  2704. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2705. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2706. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2707. };
  2708. /**
  2709. * Gets the distance between the vectors "value1" and "value2"
  2710. * @param value1 defines first vector
  2711. * @param value2 defines second vector
  2712. * @returns the distance between vectors
  2713. */
  2714. Vector2.Distance = function (value1, value2) {
  2715. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2716. };
  2717. /**
  2718. * Returns the squared distance between the vectors "value1" and "value2"
  2719. * @param value1 defines first vector
  2720. * @param value2 defines second vector
  2721. * @returns the squared distance between vectors
  2722. */
  2723. Vector2.DistanceSquared = function (value1, value2) {
  2724. var x = value1.x - value2.x;
  2725. var y = value1.y - value2.y;
  2726. return (x * x) + (y * y);
  2727. };
  2728. /**
  2729. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2730. * @param value1 defines first vector
  2731. * @param value2 defines second vector
  2732. * @returns a new Vector2
  2733. */
  2734. Vector2.Center = function (value1, value2) {
  2735. var center = value1.add(value2);
  2736. center.scaleInPlace(0.5);
  2737. return center;
  2738. };
  2739. /**
  2740. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2741. * @param p defines the middle point
  2742. * @param segA defines one point of the segment
  2743. * @param segB defines the other point of the segment
  2744. * @returns the shortest distance
  2745. */
  2746. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2747. var l2 = Vector2.DistanceSquared(segA, segB);
  2748. if (l2 === 0.0) {
  2749. return Vector2.Distance(p, segA);
  2750. }
  2751. var v = segB.subtract(segA);
  2752. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2753. var proj = segA.add(v.multiplyByFloats(t, t));
  2754. return Vector2.Distance(p, proj);
  2755. };
  2756. return Vector2;
  2757. }());
  2758. BABYLON.Vector2 = Vector2;
  2759. /**
  2760. * Classed used to store (x,y,z) vector representation
  2761. * A Vector3 is the main object used in 3D geometry
  2762. * It can represent etiher the coordinates of a point the space, either a direction
  2763. * Reminder: Babylon.js uses a left handed forward facing system
  2764. */
  2765. var Vector3 = /** @class */ (function () {
  2766. /**
  2767. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2768. * @param x defines the first coordinates (on X axis)
  2769. * @param y defines the second coordinates (on Y axis)
  2770. * @param z defines the third coordinates (on Z axis)
  2771. */
  2772. function Vector3(
  2773. /**
  2774. * Defines the first coordinates (on X axis)
  2775. */
  2776. x,
  2777. /**
  2778. * Defines the second coordinates (on Y axis)
  2779. */
  2780. y,
  2781. /**
  2782. * Defines the third coordinates (on Z axis)
  2783. */
  2784. z) {
  2785. this.x = x;
  2786. this.y = y;
  2787. this.z = z;
  2788. }
  2789. /**
  2790. * Creates a string representation of the Vector3
  2791. * @returns a string with the Vector3 coordinates.
  2792. */
  2793. Vector3.prototype.toString = function () {
  2794. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2795. };
  2796. /**
  2797. * Gets the class name
  2798. * @returns the string "Vector3"
  2799. */
  2800. Vector3.prototype.getClassName = function () {
  2801. return "Vector3";
  2802. };
  2803. /**
  2804. * Creates the Vector3 hash code
  2805. * @returns a number which tends to be unique between Vector3 instances
  2806. */
  2807. Vector3.prototype.getHashCode = function () {
  2808. var hash = this.x || 0;
  2809. hash = (hash * 397) ^ (this.y || 0);
  2810. hash = (hash * 397) ^ (this.z || 0);
  2811. return hash;
  2812. };
  2813. // Operators
  2814. /**
  2815. * Creates an array containing three elements : the coordinates of the Vector3
  2816. * @returns a new array of numbers
  2817. */
  2818. Vector3.prototype.asArray = function () {
  2819. var result = [];
  2820. this.toArray(result, 0);
  2821. return result;
  2822. };
  2823. /**
  2824. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2825. * @param array defines the destination array
  2826. * @param index defines the offset in the destination array
  2827. * @returns the current Vector3
  2828. */
  2829. Vector3.prototype.toArray = function (array, index) {
  2830. if (index === void 0) { index = 0; }
  2831. array[index] = this.x;
  2832. array[index + 1] = this.y;
  2833. array[index + 2] = this.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2838. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2839. */
  2840. Vector3.prototype.toQuaternion = function () {
  2841. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2842. };
  2843. /**
  2844. * Adds the given vector to the current Vector3
  2845. * @param otherVector defines the second operand
  2846. * @returns the current updated Vector3
  2847. */
  2848. Vector3.prototype.addInPlace = function (otherVector) {
  2849. this.x += otherVector.x;
  2850. this.y += otherVector.y;
  2851. this.z += otherVector.z;
  2852. return this;
  2853. };
  2854. /**
  2855. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2856. * @param otherVector defines the second operand
  2857. * @returns the resulting Vector3
  2858. */
  2859. Vector3.prototype.add = function (otherVector) {
  2860. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2861. };
  2862. /**
  2863. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2864. * @param otherVector defines the second operand
  2865. * @param result defines the Vector3 object where to store the result
  2866. * @returns the current Vector3
  2867. */
  2868. Vector3.prototype.addToRef = function (otherVector, result) {
  2869. result.x = this.x + otherVector.x;
  2870. result.y = this.y + otherVector.y;
  2871. result.z = this.z + otherVector.z;
  2872. return this;
  2873. };
  2874. /**
  2875. * Subtract the given vector from the current Vector3
  2876. * @param otherVector defines the second operand
  2877. * @returns the current updated Vector3
  2878. */
  2879. Vector3.prototype.subtractInPlace = function (otherVector) {
  2880. this.x -= otherVector.x;
  2881. this.y -= otherVector.y;
  2882. this.z -= otherVector.z;
  2883. return this;
  2884. };
  2885. /**
  2886. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2887. * @param otherVector defines the second operand
  2888. * @returns the resulting Vector3
  2889. */
  2890. Vector3.prototype.subtract = function (otherVector) {
  2891. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2892. };
  2893. /**
  2894. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2895. * @param otherVector defines the second operand
  2896. * @param result defines the Vector3 object where to store the result
  2897. * @returns the current Vector3
  2898. */
  2899. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2900. result.x = this.x - otherVector.x;
  2901. result.y = this.y - otherVector.y;
  2902. result.z = this.z - otherVector.z;
  2903. return this;
  2904. };
  2905. /**
  2906. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2907. * @param x defines the x coordinate of the operand
  2908. * @param y defines the y coordinate of the operand
  2909. * @param z defines the z coordinate of the operand
  2910. * @returns the resulting Vector3
  2911. */
  2912. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2913. return new Vector3(this.x - x, this.y - y, this.z - z);
  2914. };
  2915. /**
  2916. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2917. * @param x defines the x coordinate of the operand
  2918. * @param y defines the y coordinate of the operand
  2919. * @param z defines the z coordinate of the operand
  2920. * @param result defines the Vector3 object where to store the result
  2921. * @returns the current Vector3
  2922. */
  2923. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2924. result.x = this.x - x;
  2925. result.y = this.y - y;
  2926. result.z = this.z - z;
  2927. return this;
  2928. };
  2929. /**
  2930. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2931. * @returns a new Vector3
  2932. */
  2933. Vector3.prototype.negate = function () {
  2934. return new Vector3(-this.x, -this.y, -this.z);
  2935. };
  2936. /**
  2937. * Multiplies the Vector3 coordinates by the float "scale"
  2938. * @param scale defines the multiplier factor
  2939. * @returns the current updated Vector3
  2940. */
  2941. Vector3.prototype.scaleInPlace = function (scale) {
  2942. this.x *= scale;
  2943. this.y *= scale;
  2944. this.z *= scale;
  2945. return this;
  2946. };
  2947. /**
  2948. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2949. * @param scale defines the multiplier factor
  2950. * @returns a new Vector3
  2951. */
  2952. Vector3.prototype.scale = function (scale) {
  2953. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2954. };
  2955. /**
  2956. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2957. * @param scale defines the multiplier factor
  2958. * @param result defines the Vector3 object where to store the result
  2959. * @returns the current Vector3
  2960. */
  2961. Vector3.prototype.scaleToRef = function (scale, result) {
  2962. result.x = this.x * scale;
  2963. result.y = this.y * scale;
  2964. result.z = this.z * scale;
  2965. return this;
  2966. };
  2967. /**
  2968. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2969. * @param scale defines the scale factor
  2970. * @param result defines the Vector3 object where to store the result
  2971. * @returns the unmodified current Vector3
  2972. */
  2973. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2974. result.x += this.x * scale;
  2975. result.y += this.y * scale;
  2976. result.z += this.z * scale;
  2977. return this;
  2978. };
  2979. /**
  2980. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2981. * @param otherVector defines the second operand
  2982. * @returns true if both vectors are equals
  2983. */
  2984. Vector3.prototype.equals = function (otherVector) {
  2985. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2986. };
  2987. /**
  2988. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2989. * @param otherVector defines the second operand
  2990. * @param epsilon defines the minimal distance to define values as equals
  2991. * @returns true if both vectors are distant less than epsilon
  2992. */
  2993. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2994. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2995. 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);
  2996. };
  2997. /**
  2998. * Returns true if the current Vector3 coordinates equals the given floats
  2999. * @param x defines the x coordinate of the operand
  3000. * @param y defines the y coordinate of the operand
  3001. * @param z defines the z coordinate of the operand
  3002. * @returns true if both vectors are equals
  3003. */
  3004. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3005. return this.x === x && this.y === y && this.z === z;
  3006. };
  3007. /**
  3008. * Multiplies the current Vector3 coordinates by the given ones
  3009. * @param otherVector defines the second operand
  3010. * @returns the current updated Vector3
  3011. */
  3012. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3013. this.x *= otherVector.x;
  3014. this.y *= otherVector.y;
  3015. this.z *= otherVector.z;
  3016. return this;
  3017. };
  3018. /**
  3019. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3020. * @param otherVector defines the second operand
  3021. * @returns the new Vector3
  3022. */
  3023. Vector3.prototype.multiply = function (otherVector) {
  3024. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3025. };
  3026. /**
  3027. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3028. * @param otherVector defines the second operand
  3029. * @param result defines the Vector3 object where to store the result
  3030. * @returns the current Vector3
  3031. */
  3032. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3033. result.x = this.x * otherVector.x;
  3034. result.y = this.y * otherVector.y;
  3035. result.z = this.z * otherVector.z;
  3036. return this;
  3037. };
  3038. /**
  3039. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3040. * @param x defines the x coordinate of the operand
  3041. * @param y defines the y coordinate of the operand
  3042. * @param z defines the z coordinate of the operand
  3043. * @returns the new Vector3
  3044. */
  3045. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3046. return new Vector3(this.x * x, this.y * y, this.z * z);
  3047. };
  3048. /**
  3049. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3050. * @param otherVector defines the second operand
  3051. * @returns the new Vector3
  3052. */
  3053. Vector3.prototype.divide = function (otherVector) {
  3054. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3055. };
  3056. /**
  3057. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3058. * @param otherVector defines the second operand
  3059. * @param result defines the Vector3 object where to store the result
  3060. * @returns the current Vector3
  3061. */
  3062. Vector3.prototype.divideToRef = function (otherVector, result) {
  3063. result.x = this.x / otherVector.x;
  3064. result.y = this.y / otherVector.y;
  3065. result.z = this.z / otherVector.z;
  3066. return this;
  3067. };
  3068. /**
  3069. * Divides the current Vector3 coordinates by the given ones.
  3070. * @param otherVector defines the second operand
  3071. * @returns the current updated Vector3
  3072. */
  3073. Vector3.prototype.divideInPlace = function (otherVector) {
  3074. return this.divideToRef(otherVector, this);
  3075. };
  3076. /**
  3077. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3078. * @param other defines the second operand
  3079. * @returns the current updated Vector3
  3080. */
  3081. Vector3.prototype.minimizeInPlace = function (other) {
  3082. if (other.x < this.x)
  3083. this.x = other.x;
  3084. if (other.y < this.y)
  3085. this.y = other.y;
  3086. if (other.z < this.z)
  3087. this.z = other.z;
  3088. return this;
  3089. };
  3090. /**
  3091. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3092. * @param other defines the second operand
  3093. * @returns the current updated Vector3
  3094. */
  3095. Vector3.prototype.maximizeInPlace = function (other) {
  3096. if (other.x > this.x)
  3097. this.x = other.x;
  3098. if (other.y > this.y)
  3099. this.y = other.y;
  3100. if (other.z > this.z)
  3101. this.z = other.z;
  3102. return this;
  3103. };
  3104. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3105. /**
  3106. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3107. */
  3108. get: function () {
  3109. var absX = Math.abs(this.x);
  3110. var absY = Math.abs(this.y);
  3111. if (absX !== absY) {
  3112. return true;
  3113. }
  3114. var absZ = Math.abs(this.z);
  3115. if (absX !== absZ) {
  3116. return true;
  3117. }
  3118. if (absY !== absZ) {
  3119. return true;
  3120. }
  3121. return false;
  3122. },
  3123. enumerable: true,
  3124. configurable: true
  3125. });
  3126. // Properties
  3127. /**
  3128. * Gets the length of the Vector3
  3129. * @returns the length of the Vecto3
  3130. */
  3131. Vector3.prototype.length = function () {
  3132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3133. };
  3134. /**
  3135. * Gets the squared length of the Vector3
  3136. * @returns squared length of the Vector3
  3137. */
  3138. Vector3.prototype.lengthSquared = function () {
  3139. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3140. };
  3141. /**
  3142. * Normalize the current Vector3.
  3143. * Please note that this is an in place operation.
  3144. * @returns the current updated Vector3
  3145. */
  3146. Vector3.prototype.normalize = function () {
  3147. var len = this.length();
  3148. if (len === 0 || len === 1.0)
  3149. return this;
  3150. var num = 1.0 / len;
  3151. this.x *= num;
  3152. this.y *= num;
  3153. this.z *= num;
  3154. return this;
  3155. };
  3156. /**
  3157. * Normalize the current Vector3 to a new vector
  3158. * @returns the new Vector3
  3159. */
  3160. Vector3.prototype.normalizeToNew = function () {
  3161. var normalized = new Vector3(0, 0, 0);
  3162. this.normalizeToRef(normalized);
  3163. return normalized;
  3164. };
  3165. /**
  3166. * Normalize the current Vector3 to the reference
  3167. * @param reference define the Vector3 to update
  3168. * @returns the updated Vector3
  3169. */
  3170. Vector3.prototype.normalizeToRef = function (reference) {
  3171. var len = this.length();
  3172. if (len === 0 || len === 1.0) {
  3173. reference.set(this.x, this.y, this.z);
  3174. return reference;
  3175. }
  3176. var scale = 1.0 / len;
  3177. this.scaleToRef(scale, reference);
  3178. return reference;
  3179. };
  3180. /**
  3181. * Creates a new Vector3 copied from the current Vector3
  3182. * @returns the new Vector3
  3183. */
  3184. Vector3.prototype.clone = function () {
  3185. return new Vector3(this.x, this.y, this.z);
  3186. };
  3187. /**
  3188. * Copies the given vector coordinates to the current Vector3 ones
  3189. * @param source defines the source Vector3
  3190. * @returns the current updated Vector3
  3191. */
  3192. Vector3.prototype.copyFrom = function (source) {
  3193. this.x = source.x;
  3194. this.y = source.y;
  3195. this.z = source.z;
  3196. return this;
  3197. };
  3198. /**
  3199. * Copies the given floats to the current Vector3 coordinates
  3200. * @param x defines the x coordinate of the operand
  3201. * @param y defines the y coordinate of the operand
  3202. * @param z defines the z coordinate of the operand
  3203. * @returns the current updated Vector3
  3204. */
  3205. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3206. this.x = x;
  3207. this.y = y;
  3208. this.z = z;
  3209. return this;
  3210. };
  3211. /**
  3212. * Copies the given floats to the current Vector3 coordinates
  3213. * @param x defines the x coordinate of the operand
  3214. * @param y defines the y coordinate of the operand
  3215. * @param z defines the z coordinate of the operand
  3216. * @returns the current updated Vector3
  3217. */
  3218. Vector3.prototype.set = function (x, y, z) {
  3219. return this.copyFromFloats(x, y, z);
  3220. };
  3221. // Statics
  3222. /**
  3223. * Get the clip factor between two vectors
  3224. * @param vector0 defines the first operand
  3225. * @param vector1 defines the second operand
  3226. * @param axis defines the axis to use
  3227. * @param size defines the size along the axis
  3228. * @returns the clip factor
  3229. */
  3230. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3231. var d0 = Vector3.Dot(vector0, axis) - size;
  3232. var d1 = Vector3.Dot(vector1, axis) - size;
  3233. var s = d0 / (d0 - d1);
  3234. return s;
  3235. };
  3236. /**
  3237. * Get angle between two vectors
  3238. * @param vector0 angle between vector0 and vector1
  3239. * @param vector1 angle between vector0 and vector1
  3240. * @param normal direction of the normal
  3241. * @return the angle between vector0 and vector1
  3242. */
  3243. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3244. var v0 = vector0.clone().normalize();
  3245. var v1 = vector1.clone().normalize();
  3246. var dot = Vector3.Dot(v0, v1);
  3247. var n = Vector3.Cross(v0, v1);
  3248. if (Vector3.Dot(n, normal) > 0) {
  3249. return Math.acos(dot);
  3250. }
  3251. return -Math.acos(dot);
  3252. };
  3253. /**
  3254. * Returns a new Vector3 set from the index "offset" of the given array
  3255. * @param array defines the source array
  3256. * @param offset defines the offset in the source array
  3257. * @returns the new Vector3
  3258. */
  3259. Vector3.FromArray = function (array, offset) {
  3260. if (!offset) {
  3261. offset = 0;
  3262. }
  3263. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3264. };
  3265. /**
  3266. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3267. * This function is deprecated. Use FromArray instead
  3268. * @param array defines the source array
  3269. * @param offset defines the offset in the source array
  3270. * @returns the new Vector3
  3271. */
  3272. Vector3.FromFloatArray = function (array, offset) {
  3273. return Vector3.FromArray(array, offset);
  3274. };
  3275. /**
  3276. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3277. * @param array defines the source array
  3278. * @param offset defines the offset in the source array
  3279. * @param result defines the Vector3 where to store the result
  3280. */
  3281. Vector3.FromArrayToRef = function (array, offset, result) {
  3282. result.x = array[offset];
  3283. result.y = array[offset + 1];
  3284. result.z = array[offset + 2];
  3285. };
  3286. /**
  3287. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3288. * This function is deprecated. Use FromArrayToRef instead.
  3289. * @param array defines the source array
  3290. * @param offset defines the offset in the source array
  3291. * @param result defines the Vector3 where to store the result
  3292. */
  3293. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3294. return Vector3.FromArrayToRef(array, offset, result);
  3295. };
  3296. /**
  3297. * Sets the given vector "result" with the given floats.
  3298. * @param x defines the x coordinate of the source
  3299. * @param y defines the y coordinate of the source
  3300. * @param z defines the z coordinate of the source
  3301. * @param result defines the Vector3 where to store the result
  3302. */
  3303. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3304. result.x = x;
  3305. result.y = y;
  3306. result.z = z;
  3307. };
  3308. /**
  3309. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3310. * @returns a new empty Vector3
  3311. */
  3312. Vector3.Zero = function () {
  3313. return new Vector3(0.0, 0.0, 0.0);
  3314. };
  3315. /**
  3316. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3317. * @returns a new unit Vector3
  3318. */
  3319. Vector3.One = function () {
  3320. return new Vector3(1.0, 1.0, 1.0);
  3321. };
  3322. /**
  3323. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3324. * @returns a new up Vector3
  3325. */
  3326. Vector3.Up = function () {
  3327. return new Vector3(0.0, 1.0, 0.0);
  3328. };
  3329. /**
  3330. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3331. * @returns a new forward Vector3
  3332. */
  3333. Vector3.Forward = function () {
  3334. return new Vector3(0.0, 0.0, 1.0);
  3335. };
  3336. /**
  3337. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3338. * @returns a new right Vector3
  3339. */
  3340. Vector3.Right = function () {
  3341. return new Vector3(1.0, 0.0, 0.0);
  3342. };
  3343. /**
  3344. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3345. * @returns a new left Vector3
  3346. */
  3347. Vector3.Left = function () {
  3348. return new Vector3(-1.0, 0.0, 0.0);
  3349. };
  3350. /**
  3351. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3352. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3353. * @param vector defines the Vector3 to transform
  3354. * @param transformation defines the transformation matrix
  3355. * @returns the transformed Vector3
  3356. */
  3357. Vector3.TransformCoordinates = function (vector, transformation) {
  3358. var result = Vector3.Zero();
  3359. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3360. return result;
  3361. };
  3362. /**
  3363. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3364. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3365. * @param vector defines the Vector3 to transform
  3366. * @param transformation defines the transformation matrix
  3367. * @param result defines the Vector3 where to store the result
  3368. */
  3369. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3370. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3371. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3372. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3373. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3374. result.x = x / w;
  3375. result.y = y / w;
  3376. result.z = z / w;
  3377. };
  3378. /**
  3379. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3380. * This method computes tranformed coordinates only, not transformed direction vectors
  3381. * @param x define the x coordinate of the source vector
  3382. * @param y define the y coordinate of the source vector
  3383. * @param z define the z coordinate of the source vector
  3384. * @param transformation defines the transformation matrix
  3385. * @param result defines the Vector3 where to store the result
  3386. */
  3387. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3388. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3389. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3390. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3391. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3392. result.x = rx / rw;
  3393. result.y = ry / rw;
  3394. result.z = rz / rw;
  3395. };
  3396. /**
  3397. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3398. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3399. * @param vector defines the Vector3 to transform
  3400. * @param transformation defines the transformation matrix
  3401. * @returns the new Vector3
  3402. */
  3403. Vector3.TransformNormal = function (vector, transformation) {
  3404. var result = Vector3.Zero();
  3405. Vector3.TransformNormalToRef(vector, transformation, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3410. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3411. * @param vector defines the Vector3 to transform
  3412. * @param transformation defines the transformation matrix
  3413. * @param result defines the Vector3 where to store the result
  3414. */
  3415. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3416. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3417. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3418. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3419. result.x = x;
  3420. result.y = y;
  3421. result.z = z;
  3422. };
  3423. /**
  3424. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3425. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3426. * @param x define the x coordinate of the source vector
  3427. * @param y define the y coordinate of the source vector
  3428. * @param z define the z coordinate of the source vector
  3429. * @param transformation defines the transformation matrix
  3430. * @param result defines the Vector3 where to store the result
  3431. */
  3432. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3433. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3434. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3435. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3436. };
  3437. /**
  3438. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3439. * @param value1 defines the first control point
  3440. * @param value2 defines the second control point
  3441. * @param value3 defines the third control point
  3442. * @param value4 defines the fourth control point
  3443. * @param amount defines the amount on the spline to use
  3444. * @returns the new Vector3
  3445. */
  3446. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3447. var squared = amount * amount;
  3448. var cubed = amount * squared;
  3449. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3450. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3451. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3452. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3453. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3454. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3455. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3456. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3457. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3458. return new Vector3(x, y, z);
  3459. };
  3460. /**
  3461. * 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"
  3462. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3463. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3464. * @param value defines the current value
  3465. * @param min defines the lower range value
  3466. * @param max defines the upper range value
  3467. * @returns the new Vector3
  3468. */
  3469. Vector3.Clamp = function (value, min, max) {
  3470. var x = value.x;
  3471. x = (x > max.x) ? max.x : x;
  3472. x = (x < min.x) ? min.x : x;
  3473. var y = value.y;
  3474. y = (y > max.y) ? max.y : y;
  3475. y = (y < min.y) ? min.y : y;
  3476. var z = value.z;
  3477. z = (z > max.z) ? max.z : z;
  3478. z = (z < min.z) ? min.z : z;
  3479. return new Vector3(x, y, z);
  3480. };
  3481. /**
  3482. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3483. * @param value1 defines the first control point
  3484. * @param tangent1 defines the first tangent vector
  3485. * @param value2 defines the second control point
  3486. * @param tangent2 defines the second tangent vector
  3487. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3488. * @returns the new Vector3
  3489. */
  3490. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3491. var squared = amount * amount;
  3492. var cubed = amount * squared;
  3493. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3494. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3495. var part3 = (cubed - (2.0 * squared)) + amount;
  3496. var part4 = cubed - squared;
  3497. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3498. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3499. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3500. return new Vector3(x, y, z);
  3501. };
  3502. /**
  3503. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3504. * @param start defines the start value
  3505. * @param end defines the end value
  3506. * @param amount max defines amount between both (between 0 and 1)
  3507. * @returns the new Vector3
  3508. */
  3509. Vector3.Lerp = function (start, end, amount) {
  3510. var result = new Vector3(0, 0, 0);
  3511. Vector3.LerpToRef(start, end, amount, result);
  3512. return result;
  3513. };
  3514. /**
  3515. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3516. * @param start defines the start value
  3517. * @param end defines the end value
  3518. * @param amount max defines amount between both (between 0 and 1)
  3519. * @param result defines the Vector3 where to store the result
  3520. */
  3521. Vector3.LerpToRef = function (start, end, amount, result) {
  3522. result.x = start.x + ((end.x - start.x) * amount);
  3523. result.y = start.y + ((end.y - start.y) * amount);
  3524. result.z = start.z + ((end.z - start.z) * amount);
  3525. };
  3526. /**
  3527. * Returns the dot product (float) between the vectors "left" and "right"
  3528. * @param left defines the left operand
  3529. * @param right defines the right operand
  3530. * @returns the dot product
  3531. */
  3532. Vector3.Dot = function (left, right) {
  3533. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3534. };
  3535. /**
  3536. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3537. * The cross product is then orthogonal to both "left" and "right"
  3538. * @param left defines the left operand
  3539. * @param right defines the right operand
  3540. * @returns the cross product
  3541. */
  3542. Vector3.Cross = function (left, right) {
  3543. var result = Vector3.Zero();
  3544. Vector3.CrossToRef(left, right, result);
  3545. return result;
  3546. };
  3547. /**
  3548. * Sets the given vector "result" with the cross product of "left" and "right"
  3549. * The cross product is then orthogonal to both "left" and "right"
  3550. * @param left defines the left operand
  3551. * @param right defines the right operand
  3552. * @param result defines the Vector3 where to store the result
  3553. */
  3554. Vector3.CrossToRef = function (left, right, result) {
  3555. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3556. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3557. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3558. result.copyFrom(MathTmp.Vector3[0]);
  3559. };
  3560. /**
  3561. * Returns a new Vector3 as the normalization of the given vector
  3562. * @param vector defines the Vector3 to normalize
  3563. * @returns the new Vector3
  3564. */
  3565. Vector3.Normalize = function (vector) {
  3566. var result = Vector3.Zero();
  3567. Vector3.NormalizeToRef(vector, result);
  3568. return result;
  3569. };
  3570. /**
  3571. * Sets the given vector "result" with the normalization of the given first vector
  3572. * @param vector defines the Vector3 to normalize
  3573. * @param result defines the Vector3 where to store the result
  3574. */
  3575. Vector3.NormalizeToRef = function (vector, result) {
  3576. result.copyFrom(vector);
  3577. result.normalize();
  3578. };
  3579. /**
  3580. * Project a Vector3 onto screen space
  3581. * @param vector defines the Vector3 to project
  3582. * @param world defines the world matrix to use
  3583. * @param transform defines the transform (view x projection) matrix to use
  3584. * @param viewport defines the screen viewport to use
  3585. * @returns the new Vector3
  3586. */
  3587. Vector3.Project = function (vector, world, transform, viewport) {
  3588. var cw = viewport.width;
  3589. var ch = viewport.height;
  3590. var cx = viewport.x;
  3591. var cy = viewport.y;
  3592. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3593. 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);
  3594. var matrix = MathTmp.Matrix[0];
  3595. world.multiplyToRef(transform, matrix);
  3596. matrix.multiplyToRef(viewportMatrix, matrix);
  3597. return Vector3.TransformCoordinates(vector, matrix);
  3598. };
  3599. /**
  3600. * Unproject from screen space to object space
  3601. * @param source defines the screen space Vector3 to use
  3602. * @param viewportWidth defines the current width of the viewport
  3603. * @param viewportHeight defines the current height of the viewport
  3604. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3605. * @param transform defines the transform (view x projection) matrix to use
  3606. * @returns the new Vector3
  3607. */
  3608. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3609. var matrix = MathTmp.Matrix[0];
  3610. world.multiplyToRef(transform, matrix);
  3611. matrix.invert();
  3612. source.x = source.x / viewportWidth * 2 - 1;
  3613. source.y = -(source.y / viewportHeight * 2 - 1);
  3614. var vector = Vector3.TransformCoordinates(source, matrix);
  3615. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3616. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3617. vector = vector.scale(1.0 / num);
  3618. }
  3619. return vector;
  3620. };
  3621. /**
  3622. * Unproject from screen space to object space
  3623. * @param source defines the screen space Vector3 to use
  3624. * @param viewportWidth defines the current width of the viewport
  3625. * @param viewportHeight defines the current height of the viewport
  3626. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3627. * @param view defines the view matrix to use
  3628. * @param projection defines the projection matrix to use
  3629. * @returns the new Vector3
  3630. */
  3631. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3632. var result = Vector3.Zero();
  3633. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3634. return result;
  3635. };
  3636. /**
  3637. * Unproject from screen space to object space
  3638. * @param source defines the screen space Vector3 to use
  3639. * @param viewportWidth defines the current width of the viewport
  3640. * @param viewportHeight defines the current height of the viewport
  3641. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3642. * @param view defines the view matrix to use
  3643. * @param projection defines the projection matrix to use
  3644. * @param result defines the Vector3 where to store the result
  3645. */
  3646. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3647. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3648. };
  3649. /**
  3650. * Unproject from screen space to object space
  3651. * @param sourceX defines the screen space x coordinate to use
  3652. * @param sourceY defines the screen space y coordinate to use
  3653. * @param sourceZ defines the screen space z coordinate to use
  3654. * @param viewportWidth defines the current width of the viewport
  3655. * @param viewportHeight defines the current height of the viewport
  3656. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3657. * @param view defines the view matrix to use
  3658. * @param projection defines the projection matrix to use
  3659. * @param result defines the Vector3 where to store the result
  3660. */
  3661. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3662. var matrix = MathTmp.Matrix[0];
  3663. world.multiplyToRef(view, matrix);
  3664. matrix.multiplyToRef(projection, matrix);
  3665. matrix.invert();
  3666. var screenSource = MathTmp.Vector3[0];
  3667. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3668. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3669. screenSource.z = 2 * sourceZ - 1.0;
  3670. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3671. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3672. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3673. result.scaleInPlace(1.0 / num);
  3674. }
  3675. };
  3676. /**
  3677. * Gets the minimal coordinate values between two Vector3
  3678. * @param left defines the first operand
  3679. * @param right defines the second operand
  3680. * @returns the new Vector3
  3681. */
  3682. Vector3.Minimize = function (left, right) {
  3683. var min = left.clone();
  3684. min.minimizeInPlace(right);
  3685. return min;
  3686. };
  3687. /**
  3688. * Gets the maximal coordinate values between two Vector3
  3689. * @param left defines the first operand
  3690. * @param right defines the second operand
  3691. * @returns the new Vector3
  3692. */
  3693. Vector3.Maximize = function (left, right) {
  3694. var max = left.clone();
  3695. max.maximizeInPlace(right);
  3696. return max;
  3697. };
  3698. /**
  3699. * Returns the distance between the vectors "value1" and "value2"
  3700. * @param value1 defines the first operand
  3701. * @param value2 defines the second operand
  3702. * @returns the distance
  3703. */
  3704. Vector3.Distance = function (value1, value2) {
  3705. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3706. };
  3707. /**
  3708. * Returns the squared distance between the vectors "value1" and "value2"
  3709. * @param value1 defines the first operand
  3710. * @param value2 defines the second operand
  3711. * @returns the squared distance
  3712. */
  3713. Vector3.DistanceSquared = function (value1, value2) {
  3714. var x = value1.x - value2.x;
  3715. var y = value1.y - value2.y;
  3716. var z = value1.z - value2.z;
  3717. return (x * x) + (y * y) + (z * z);
  3718. };
  3719. /**
  3720. * Returns a new Vector3 located at the center between "value1" and "value2"
  3721. * @param value1 defines the first operand
  3722. * @param value2 defines the second operand
  3723. * @returns the new Vector3
  3724. */
  3725. Vector3.Center = function (value1, value2) {
  3726. var center = value1.add(value2);
  3727. center.scaleInPlace(0.5);
  3728. return center;
  3729. };
  3730. /**
  3731. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3732. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3733. * to something in order to rotate it from its local system to the given target system
  3734. * Note: axis1, axis2 and axis3 are normalized during this operation
  3735. * @param axis1 defines the first axis
  3736. * @param axis2 defines the second axis
  3737. * @param axis3 defines the third axis
  3738. * @returns a new Vector3
  3739. */
  3740. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3741. var rotation = Vector3.Zero();
  3742. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3743. return rotation;
  3744. };
  3745. /**
  3746. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3747. * @param axis1 defines the first axis
  3748. * @param axis2 defines the second axis
  3749. * @param axis3 defines the third axis
  3750. * @param ref defines the Vector3 where to store the result
  3751. */
  3752. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3753. var quat = MathTmp.Quaternion[0];
  3754. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3755. quat.toEulerAnglesToRef(ref);
  3756. };
  3757. return Vector3;
  3758. }());
  3759. BABYLON.Vector3 = Vector3;
  3760. //Vector4 class created for EulerAngle class conversion to Quaternion
  3761. var Vector4 = /** @class */ (function () {
  3762. /**
  3763. * Creates a Vector4 object from the given floats.
  3764. */
  3765. function Vector4(x, y, z, w) {
  3766. this.x = x;
  3767. this.y = y;
  3768. this.z = z;
  3769. this.w = w;
  3770. }
  3771. /**
  3772. * Returns the string with the Vector4 coordinates.
  3773. */
  3774. Vector4.prototype.toString = function () {
  3775. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3776. };
  3777. /**
  3778. * Returns the string "Vector4".
  3779. */
  3780. Vector4.prototype.getClassName = function () {
  3781. return "Vector4";
  3782. };
  3783. /**
  3784. * Returns the Vector4 hash code.
  3785. */
  3786. Vector4.prototype.getHashCode = function () {
  3787. var hash = this.x || 0;
  3788. hash = (hash * 397) ^ (this.y || 0);
  3789. hash = (hash * 397) ^ (this.z || 0);
  3790. hash = (hash * 397) ^ (this.w || 0);
  3791. return hash;
  3792. };
  3793. // Operators
  3794. /**
  3795. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3796. */
  3797. Vector4.prototype.asArray = function () {
  3798. var result = new Array();
  3799. this.toArray(result, 0);
  3800. return result;
  3801. };
  3802. /**
  3803. * Populates the given array from the given index with the Vector4 coordinates.
  3804. * Returns the Vector4.
  3805. */
  3806. Vector4.prototype.toArray = function (array, index) {
  3807. if (index === undefined) {
  3808. index = 0;
  3809. }
  3810. array[index] = this.x;
  3811. array[index + 1] = this.y;
  3812. array[index + 2] = this.z;
  3813. array[index + 3] = this.w;
  3814. return this;
  3815. };
  3816. /**
  3817. * Adds the given vector to the current Vector4.
  3818. * Returns the updated Vector4.
  3819. */
  3820. Vector4.prototype.addInPlace = function (otherVector) {
  3821. this.x += otherVector.x;
  3822. this.y += otherVector.y;
  3823. this.z += otherVector.z;
  3824. this.w += otherVector.w;
  3825. return this;
  3826. };
  3827. /**
  3828. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3829. */
  3830. Vector4.prototype.add = function (otherVector) {
  3831. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3832. };
  3833. /**
  3834. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3835. * Returns the current Vector4.
  3836. */
  3837. Vector4.prototype.addToRef = function (otherVector, result) {
  3838. result.x = this.x + otherVector.x;
  3839. result.y = this.y + otherVector.y;
  3840. result.z = this.z + otherVector.z;
  3841. result.w = this.w + otherVector.w;
  3842. return this;
  3843. };
  3844. /**
  3845. * Subtract in place the given vector from the current Vector4.
  3846. * Returns the updated Vector4.
  3847. */
  3848. Vector4.prototype.subtractInPlace = function (otherVector) {
  3849. this.x -= otherVector.x;
  3850. this.y -= otherVector.y;
  3851. this.z -= otherVector.z;
  3852. this.w -= otherVector.w;
  3853. return this;
  3854. };
  3855. /**
  3856. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3857. */
  3858. Vector4.prototype.subtract = function (otherVector) {
  3859. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3860. };
  3861. /**
  3862. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3863. * Returns the current Vector4.
  3864. */
  3865. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3866. result.x = this.x - otherVector.x;
  3867. result.y = this.y - otherVector.y;
  3868. result.z = this.z - otherVector.z;
  3869. result.w = this.w - otherVector.w;
  3870. return this;
  3871. };
  3872. /**
  3873. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3874. */
  3875. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3876. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3877. };
  3878. /**
  3879. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3880. * Returns the current Vector4.
  3881. */
  3882. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3883. result.x = this.x - x;
  3884. result.y = this.y - y;
  3885. result.z = this.z - z;
  3886. result.w = this.w - w;
  3887. return this;
  3888. };
  3889. /**
  3890. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3891. */
  3892. Vector4.prototype.negate = function () {
  3893. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3894. };
  3895. /**
  3896. * Multiplies the current Vector4 coordinates by scale (float).
  3897. * Returns the updated Vector4.
  3898. */
  3899. Vector4.prototype.scaleInPlace = function (scale) {
  3900. this.x *= scale;
  3901. this.y *= scale;
  3902. this.z *= scale;
  3903. this.w *= scale;
  3904. return this;
  3905. };
  3906. /**
  3907. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3908. */
  3909. Vector4.prototype.scale = function (scale) {
  3910. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3911. };
  3912. /**
  3913. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3914. * Returns the current Vector4.
  3915. */
  3916. Vector4.prototype.scaleToRef = function (scale, result) {
  3917. result.x = this.x * scale;
  3918. result.y = this.y * scale;
  3919. result.z = this.z * scale;
  3920. result.w = this.w * scale;
  3921. return this;
  3922. };
  3923. /**
  3924. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3925. * @param scale defines the scale factor
  3926. * @param result defines the Vector4 object where to store the result
  3927. * @returns the unmodified current Vector4
  3928. */
  3929. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3930. result.x += this.x * scale;
  3931. result.y += this.y * scale;
  3932. result.z += this.z * scale;
  3933. result.w += this.w * scale;
  3934. return this;
  3935. };
  3936. /**
  3937. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3938. */
  3939. Vector4.prototype.equals = function (otherVector) {
  3940. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3941. };
  3942. /**
  3943. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3944. */
  3945. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3946. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3947. return otherVector
  3948. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3949. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3950. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3951. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3952. };
  3953. /**
  3954. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3955. */
  3956. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3957. return this.x === x && this.y === y && this.z === z && this.w === w;
  3958. };
  3959. /**
  3960. * Multiplies in place the current Vector4 by the given one.
  3961. * Returns the updated Vector4.
  3962. */
  3963. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3964. this.x *= otherVector.x;
  3965. this.y *= otherVector.y;
  3966. this.z *= otherVector.z;
  3967. this.w *= otherVector.w;
  3968. return this;
  3969. };
  3970. /**
  3971. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3972. */
  3973. Vector4.prototype.multiply = function (otherVector) {
  3974. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3975. };
  3976. /**
  3977. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3978. * Returns the current Vector4.
  3979. */
  3980. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3981. result.x = this.x * otherVector.x;
  3982. result.y = this.y * otherVector.y;
  3983. result.z = this.z * otherVector.z;
  3984. result.w = this.w * otherVector.w;
  3985. return this;
  3986. };
  3987. /**
  3988. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3989. */
  3990. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3991. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3992. };
  3993. /**
  3994. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3995. */
  3996. Vector4.prototype.divide = function (otherVector) {
  3997. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3998. };
  3999. /**
  4000. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4001. * Returns the current Vector4.
  4002. */
  4003. Vector4.prototype.divideToRef = function (otherVector, result) {
  4004. result.x = this.x / otherVector.x;
  4005. result.y = this.y / otherVector.y;
  4006. result.z = this.z / otherVector.z;
  4007. result.w = this.w / otherVector.w;
  4008. return this;
  4009. };
  4010. /**
  4011. * Divides the current Vector3 coordinates by the given ones.
  4012. * @returns the updated Vector3.
  4013. */
  4014. Vector4.prototype.divideInPlace = function (otherVector) {
  4015. return this.divideToRef(otherVector, this);
  4016. };
  4017. /**
  4018. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4019. * @param other defines the second operand
  4020. * @returns the current updated Vector4
  4021. */
  4022. Vector4.prototype.minimizeInPlace = function (other) {
  4023. if (other.x < this.x)
  4024. this.x = other.x;
  4025. if (other.y < this.y)
  4026. this.y = other.y;
  4027. if (other.z < this.z)
  4028. this.z = other.z;
  4029. if (other.w < this.w)
  4030. this.w = other.w;
  4031. return this;
  4032. };
  4033. /**
  4034. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4035. * @param other defines the second operand
  4036. * @returns the current updated Vector4
  4037. */
  4038. Vector4.prototype.maximizeInPlace = function (other) {
  4039. if (other.x > this.x)
  4040. this.x = other.x;
  4041. if (other.y > this.y)
  4042. this.y = other.y;
  4043. if (other.z > this.z)
  4044. this.z = other.z;
  4045. if (other.w > this.w)
  4046. this.w = other.w;
  4047. return this;
  4048. };
  4049. // Properties
  4050. /**
  4051. * Returns the Vector4 length (float).
  4052. */
  4053. Vector4.prototype.length = function () {
  4054. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4055. };
  4056. /**
  4057. * Returns the Vector4 squared length (float).
  4058. */
  4059. Vector4.prototype.lengthSquared = function () {
  4060. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4061. };
  4062. // Methods
  4063. /**
  4064. * Normalizes in place the Vector4.
  4065. * Returns the updated Vector4.
  4066. */
  4067. Vector4.prototype.normalize = function () {
  4068. var len = this.length();
  4069. if (len === 0)
  4070. return this;
  4071. var num = 1.0 / len;
  4072. this.x *= num;
  4073. this.y *= num;
  4074. this.z *= num;
  4075. this.w *= num;
  4076. return this;
  4077. };
  4078. /**
  4079. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4080. */
  4081. Vector4.prototype.toVector3 = function () {
  4082. return new Vector3(this.x, this.y, this.z);
  4083. };
  4084. /**
  4085. * Returns a new Vector4 copied from the current one.
  4086. */
  4087. Vector4.prototype.clone = function () {
  4088. return new Vector4(this.x, this.y, this.z, this.w);
  4089. };
  4090. /**
  4091. * Updates the current Vector4 with the given one coordinates.
  4092. * Returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.copyFrom = function (source) {
  4095. this.x = source.x;
  4096. this.y = source.y;
  4097. this.z = source.z;
  4098. this.w = source.w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Updates the current Vector4 coordinates with the given floats.
  4103. * Returns the updated Vector4.
  4104. */
  4105. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4106. this.x = x;
  4107. this.y = y;
  4108. this.z = z;
  4109. this.w = w;
  4110. return this;
  4111. };
  4112. /**
  4113. * Updates the current Vector4 coordinates with the given floats.
  4114. * Returns the updated Vector4.
  4115. */
  4116. Vector4.prototype.set = function (x, y, z, w) {
  4117. return this.copyFromFloats(x, y, z, w);
  4118. };
  4119. // Statics
  4120. /**
  4121. * Returns a new Vector4 set from the starting index of the given array.
  4122. */
  4123. Vector4.FromArray = function (array, offset) {
  4124. if (!offset) {
  4125. offset = 0;
  4126. }
  4127. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4128. };
  4129. /**
  4130. * Updates the given vector "result" from the starting index of the given array.
  4131. */
  4132. Vector4.FromArrayToRef = function (array, offset, result) {
  4133. result.x = array[offset];
  4134. result.y = array[offset + 1];
  4135. result.z = array[offset + 2];
  4136. result.w = array[offset + 3];
  4137. };
  4138. /**
  4139. * Updates the given vector "result" from the starting index of the given Float32Array.
  4140. */
  4141. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4142. Vector4.FromArrayToRef(array, offset, result);
  4143. };
  4144. /**
  4145. * Updates the given vector "result" coordinates from the given floats.
  4146. */
  4147. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4148. result.x = x;
  4149. result.y = y;
  4150. result.z = z;
  4151. result.w = w;
  4152. };
  4153. /**
  4154. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4155. */
  4156. Vector4.Zero = function () {
  4157. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4158. };
  4159. /**
  4160. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4161. */
  4162. Vector4.One = function () {
  4163. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4164. };
  4165. /**
  4166. * Returns a new normalized Vector4 from the given one.
  4167. */
  4168. Vector4.Normalize = function (vector) {
  4169. var result = Vector4.Zero();
  4170. Vector4.NormalizeToRef(vector, result);
  4171. return result;
  4172. };
  4173. /**
  4174. * Updates the given vector "result" from the normalization of the given one.
  4175. */
  4176. Vector4.NormalizeToRef = function (vector, result) {
  4177. result.copyFrom(vector);
  4178. result.normalize();
  4179. };
  4180. Vector4.Minimize = function (left, right) {
  4181. var min = left.clone();
  4182. min.minimizeInPlace(right);
  4183. return min;
  4184. };
  4185. Vector4.Maximize = function (left, right) {
  4186. var max = left.clone();
  4187. max.maximizeInPlace(right);
  4188. return max;
  4189. };
  4190. /**
  4191. * Returns the distance (float) between the vectors "value1" and "value2".
  4192. */
  4193. Vector4.Distance = function (value1, value2) {
  4194. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4195. };
  4196. /**
  4197. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4198. */
  4199. Vector4.DistanceSquared = function (value1, value2) {
  4200. var x = value1.x - value2.x;
  4201. var y = value1.y - value2.y;
  4202. var z = value1.z - value2.z;
  4203. var w = value1.w - value2.w;
  4204. return (x * x) + (y * y) + (z * z) + (w * w);
  4205. };
  4206. /**
  4207. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4208. */
  4209. Vector4.Center = function (value1, value2) {
  4210. var center = value1.add(value2);
  4211. center.scaleInPlace(0.5);
  4212. return center;
  4213. };
  4214. /**
  4215. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4216. * This methods computes transformed normalized direction vectors only.
  4217. */
  4218. Vector4.TransformNormal = function (vector, transformation) {
  4219. var result = Vector4.Zero();
  4220. Vector4.TransformNormalToRef(vector, transformation, result);
  4221. return result;
  4222. };
  4223. /**
  4224. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4225. * This methods computes transformed normalized direction vectors only.
  4226. */
  4227. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4228. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4229. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4230. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4231. result.x = x;
  4232. result.y = y;
  4233. result.z = z;
  4234. result.w = vector.w;
  4235. };
  4236. /**
  4237. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4238. * This methods computes transformed normalized direction vectors only.
  4239. */
  4240. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4241. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4242. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4243. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4244. result.w = w;
  4245. };
  4246. return Vector4;
  4247. }());
  4248. BABYLON.Vector4 = Vector4;
  4249. var Size = /** @class */ (function () {
  4250. /**
  4251. * Creates a Size object from the given width and height (floats).
  4252. */
  4253. function Size(width, height) {
  4254. this.width = width;
  4255. this.height = height;
  4256. }
  4257. // Returns a string with the Size width and height.
  4258. Size.prototype.toString = function () {
  4259. return "{W: " + this.width + ", H: " + this.height + "}";
  4260. };
  4261. /**
  4262. * Returns the string "Size"
  4263. */
  4264. Size.prototype.getClassName = function () {
  4265. return "Size";
  4266. };
  4267. /**
  4268. * Returns the Size hash code.
  4269. */
  4270. Size.prototype.getHashCode = function () {
  4271. var hash = this.width || 0;
  4272. hash = (hash * 397) ^ (this.height || 0);
  4273. return hash;
  4274. };
  4275. /**
  4276. * Updates the current size from the given one.
  4277. * Returns the updated Size.
  4278. */
  4279. Size.prototype.copyFrom = function (src) {
  4280. this.width = src.width;
  4281. this.height = src.height;
  4282. };
  4283. /**
  4284. * Updates in place the current Size from the given floats.
  4285. * Returns the updated Size.
  4286. */
  4287. Size.prototype.copyFromFloats = function (width, height) {
  4288. this.width = width;
  4289. this.height = height;
  4290. return this;
  4291. };
  4292. /**
  4293. * Updates in place the current Size from the given floats.
  4294. * Returns the updated Size.
  4295. */
  4296. Size.prototype.set = function (width, height) {
  4297. return this.copyFromFloats(width, height);
  4298. };
  4299. /**
  4300. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4301. */
  4302. Size.prototype.multiplyByFloats = function (w, h) {
  4303. return new Size(this.width * w, this.height * h);
  4304. };
  4305. /**
  4306. * Returns a new Size copied from the given one.
  4307. */
  4308. Size.prototype.clone = function () {
  4309. return new Size(this.width, this.height);
  4310. };
  4311. /**
  4312. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4313. */
  4314. Size.prototype.equals = function (other) {
  4315. if (!other) {
  4316. return false;
  4317. }
  4318. return (this.width === other.width) && (this.height === other.height);
  4319. };
  4320. Object.defineProperty(Size.prototype, "surface", {
  4321. /**
  4322. * Returns the surface of the Size : width * height (float).
  4323. */
  4324. get: function () {
  4325. return this.width * this.height;
  4326. },
  4327. enumerable: true,
  4328. configurable: true
  4329. });
  4330. /**
  4331. * Returns a new Size set to (0.0, 0.0)
  4332. */
  4333. Size.Zero = function () {
  4334. return new Size(0.0, 0.0);
  4335. };
  4336. /**
  4337. * Returns a new Size set as the addition result of the current Size and the given one.
  4338. */
  4339. Size.prototype.add = function (otherSize) {
  4340. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4341. return r;
  4342. };
  4343. /**
  4344. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4345. */
  4346. Size.prototype.subtract = function (otherSize) {
  4347. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4348. return r;
  4349. };
  4350. /**
  4351. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4352. */
  4353. Size.Lerp = function (start, end, amount) {
  4354. var w = start.width + ((end.width - start.width) * amount);
  4355. var h = start.height + ((end.height - start.height) * amount);
  4356. return new Size(w, h);
  4357. };
  4358. return Size;
  4359. }());
  4360. BABYLON.Size = Size;
  4361. /**
  4362. * Class used to store quaternion data
  4363. * @see https://en.wikipedia.org/wiki/Quaternion
  4364. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4365. */
  4366. var Quaternion = /** @class */ (function () {
  4367. /**
  4368. * Creates a new Quaternion from the given floats
  4369. * @param x defines the first component (0 by default)
  4370. * @param y defines the second component (0 by default)
  4371. * @param z defines the third component (0 by default)
  4372. * @param w defines the fourth component (1.0 by default)
  4373. */
  4374. function Quaternion(
  4375. /** defines the first component (0 by default) */
  4376. x,
  4377. /** defines the second component (0 by default) */
  4378. y,
  4379. /** defines the third component (0 by default) */
  4380. z,
  4381. /** defines the fourth component (1.0 by default) */
  4382. w) {
  4383. if (x === void 0) { x = 0.0; }
  4384. if (y === void 0) { y = 0.0; }
  4385. if (z === void 0) { z = 0.0; }
  4386. if (w === void 0) { w = 1.0; }
  4387. this.x = x;
  4388. this.y = y;
  4389. this.z = z;
  4390. this.w = w;
  4391. }
  4392. /**
  4393. * Gets a string representation for the current quaternion
  4394. * @returns a string with the Quaternion coordinates
  4395. */
  4396. Quaternion.prototype.toString = function () {
  4397. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4398. };
  4399. /**
  4400. * Gets the class name of the quaternion
  4401. * @returns the string "Quaternion"
  4402. */
  4403. Quaternion.prototype.getClassName = function () {
  4404. return "Quaternion";
  4405. };
  4406. /**
  4407. * Gets a hash code for this quaternion
  4408. * @returns the quaternion hash code
  4409. */
  4410. Quaternion.prototype.getHashCode = function () {
  4411. var hash = this.x || 0;
  4412. hash = (hash * 397) ^ (this.y || 0);
  4413. hash = (hash * 397) ^ (this.z || 0);
  4414. hash = (hash * 397) ^ (this.w || 0);
  4415. return hash;
  4416. };
  4417. /**
  4418. * Copy the quaternion to an array
  4419. * @returns a new array populated with 4 elements from the quaternion coordinates
  4420. */
  4421. Quaternion.prototype.asArray = function () {
  4422. return [this.x, this.y, this.z, this.w];
  4423. };
  4424. /**
  4425. * Check if two quaternions are equals
  4426. * @param otherQuaternion defines the second operand
  4427. * @return true if the current quaternion and the given one coordinates are strictly equals
  4428. */
  4429. Quaternion.prototype.equals = function (otherQuaternion) {
  4430. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4431. };
  4432. /**
  4433. * Clone the current quaternion
  4434. * @returns a new quaternion copied from the current one
  4435. */
  4436. Quaternion.prototype.clone = function () {
  4437. return new Quaternion(this.x, this.y, this.z, this.w);
  4438. };
  4439. /**
  4440. * Copy a quaternion to the current one
  4441. * @param other defines the other quaternion
  4442. * @returns the updated current quaternion
  4443. */
  4444. Quaternion.prototype.copyFrom = function (other) {
  4445. this.x = other.x;
  4446. this.y = other.y;
  4447. this.z = other.z;
  4448. this.w = other.w;
  4449. return this;
  4450. };
  4451. /**
  4452. * Updates the current quaternion with the given float coordinates
  4453. * @param x defines the x coordinate
  4454. * @param y defines the y coordinate
  4455. * @param z defines the z coordinate
  4456. * @param w defines the w coordinate
  4457. * @returns the updated current quaternion
  4458. */
  4459. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4460. this.x = x;
  4461. this.y = y;
  4462. this.z = z;
  4463. this.w = w;
  4464. return this;
  4465. };
  4466. /**
  4467. * Updates the current quaternion from the given float coordinates
  4468. * @param x defines the x coordinate
  4469. * @param y defines the y coordinate
  4470. * @param z defines the z coordinate
  4471. * @param w defines the w coordinate
  4472. * @returns the updated current quaternion
  4473. */
  4474. Quaternion.prototype.set = function (x, y, z, w) {
  4475. return this.copyFromFloats(x, y, z, w);
  4476. };
  4477. /**
  4478. * Adds two quaternions
  4479. * @param other defines the second operand
  4480. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4481. */
  4482. Quaternion.prototype.add = function (other) {
  4483. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4484. };
  4485. /**
  4486. * Add a quaternion to the current one
  4487. * @param other defines the quaternion to add
  4488. * @returns the current quaternion
  4489. */
  4490. Quaternion.prototype.addInPlace = function (other) {
  4491. this.x += other.x;
  4492. this.y += other.y;
  4493. this.z += other.z;
  4494. this.w += other.w;
  4495. return this;
  4496. };
  4497. /**
  4498. * Subtract two quaternions
  4499. * @param other defines the second operand
  4500. * @returns a new quaternion as the subtraction result of the given one from the current one
  4501. */
  4502. Quaternion.prototype.subtract = function (other) {
  4503. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4504. };
  4505. /**
  4506. * Multiplies the current quaternion by a scale factor
  4507. * @param value defines the scale factor
  4508. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4509. */
  4510. Quaternion.prototype.scale = function (value) {
  4511. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4512. };
  4513. /**
  4514. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4515. * @param scale defines the scale factor
  4516. * @param result defines the Quaternion object where to store the result
  4517. * @returns the unmodified current quaternion
  4518. */
  4519. Quaternion.prototype.scaleToRef = function (scale, result) {
  4520. result.x = this.x * scale;
  4521. result.y = this.y * scale;
  4522. result.z = this.z * scale;
  4523. result.w = this.w * scale;
  4524. return this;
  4525. };
  4526. /**
  4527. * Multiplies in place the current quaternion by a scale factor
  4528. * @param value defines the scale factor
  4529. * @returns the current modified quaternion
  4530. */
  4531. Quaternion.prototype.scaleInPlace = function (value) {
  4532. this.x *= value;
  4533. this.y *= value;
  4534. this.z *= value;
  4535. this.w *= value;
  4536. return this;
  4537. };
  4538. /**
  4539. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4540. * @param scale defines the scale factor
  4541. * @param result defines the Quaternion object where to store the result
  4542. * @returns the unmodified current quaternion
  4543. */
  4544. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4545. result.x += this.x * scale;
  4546. result.y += this.y * scale;
  4547. result.z += this.z * scale;
  4548. result.w += this.w * scale;
  4549. return this;
  4550. };
  4551. /**
  4552. * Multiplies two quaternions
  4553. * @param q1 defines the second operand
  4554. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4555. */
  4556. Quaternion.prototype.multiply = function (q1) {
  4557. var result = new Quaternion(0, 0, 0, 1.0);
  4558. this.multiplyToRef(q1, result);
  4559. return result;
  4560. };
  4561. /**
  4562. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4563. * @param q1 defines the second operand
  4564. * @param result defines the target quaternion
  4565. * @returns the current quaternion
  4566. */
  4567. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4568. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4569. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4570. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4571. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4572. result.copyFromFloats(x, y, z, w);
  4573. return this;
  4574. };
  4575. /**
  4576. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4577. * @param q1 defines the second operand
  4578. * @returns the currentupdated quaternion
  4579. */
  4580. Quaternion.prototype.multiplyInPlace = function (q1) {
  4581. this.multiplyToRef(q1, this);
  4582. return this;
  4583. };
  4584. /**
  4585. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4586. * @param ref defines the target quaternion
  4587. * @returns the current quaternion
  4588. */
  4589. Quaternion.prototype.conjugateToRef = function (ref) {
  4590. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4591. return this;
  4592. };
  4593. /**
  4594. * Conjugates in place (1-q) the current quaternion
  4595. * @returns the current updated quaternion
  4596. */
  4597. Quaternion.prototype.conjugateInPlace = function () {
  4598. this.x *= -1;
  4599. this.y *= -1;
  4600. this.z *= -1;
  4601. return this;
  4602. };
  4603. /**
  4604. * Conjugates in place (1-q) the current quaternion
  4605. * @returns a new quaternion
  4606. */
  4607. Quaternion.prototype.conjugate = function () {
  4608. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4609. return result;
  4610. };
  4611. /**
  4612. * Gets length of current quaternion
  4613. * @returns the quaternion length (float)
  4614. */
  4615. Quaternion.prototype.length = function () {
  4616. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4617. };
  4618. /**
  4619. * Normalize in place the current quaternion
  4620. * @returns the current updated quaternion
  4621. */
  4622. Quaternion.prototype.normalize = function () {
  4623. var length = 1.0 / this.length();
  4624. this.x *= length;
  4625. this.y *= length;
  4626. this.z *= length;
  4627. this.w *= length;
  4628. return this;
  4629. };
  4630. /**
  4631. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4632. * @param order is a reserved parameter and is ignore for now
  4633. * @returns a new Vector3 containing the Euler angles
  4634. */
  4635. Quaternion.prototype.toEulerAngles = function (order) {
  4636. if (order === void 0) { order = "YZX"; }
  4637. var result = Vector3.Zero();
  4638. this.toEulerAnglesToRef(result, order);
  4639. return result;
  4640. };
  4641. /**
  4642. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4643. * @param result defines the vector which will be filled with the Euler angles
  4644. * @param order is a reserved parameter and is ignore for now
  4645. * @returns the current unchanged quaternion
  4646. */
  4647. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4648. if (order === void 0) { order = "YZX"; }
  4649. var qz = this.z;
  4650. var qx = this.x;
  4651. var qy = this.y;
  4652. var qw = this.w;
  4653. var sqw = qw * qw;
  4654. var sqz = qz * qz;
  4655. var sqx = qx * qx;
  4656. var sqy = qy * qy;
  4657. var zAxisY = qy * qz - qx * qw;
  4658. var limit = .4999999;
  4659. if (zAxisY < -limit) {
  4660. result.y = 2 * Math.atan2(qy, qw);
  4661. result.x = Math.PI / 2;
  4662. result.z = 0;
  4663. }
  4664. else if (zAxisY > limit) {
  4665. result.y = 2 * Math.atan2(qy, qw);
  4666. result.x = -Math.PI / 2;
  4667. result.z = 0;
  4668. }
  4669. else {
  4670. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4671. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4672. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4673. }
  4674. return this;
  4675. };
  4676. /**
  4677. * Updates the given rotation matrix with the current quaternion values
  4678. * @param result defines the target matrix
  4679. * @returns the current unchanged quaternion
  4680. */
  4681. Quaternion.prototype.toRotationMatrix = function (result) {
  4682. var xx = this.x * this.x;
  4683. var yy = this.y * this.y;
  4684. var zz = this.z * this.z;
  4685. var xy = this.x * this.y;
  4686. var zw = this.z * this.w;
  4687. var zx = this.z * this.x;
  4688. var yw = this.y * this.w;
  4689. var yz = this.y * this.z;
  4690. var xw = this.x * this.w;
  4691. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4692. result.m[1] = 2.0 * (xy + zw);
  4693. result.m[2] = 2.0 * (zx - yw);
  4694. result.m[3] = 0;
  4695. result.m[4] = 2.0 * (xy - zw);
  4696. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4697. result.m[6] = 2.0 * (yz + xw);
  4698. result.m[7] = 0;
  4699. result.m[8] = 2.0 * (zx + yw);
  4700. result.m[9] = 2.0 * (yz - xw);
  4701. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4702. result.m[11] = 0;
  4703. result.m[12] = 0;
  4704. result.m[13] = 0;
  4705. result.m[14] = 0;
  4706. result.m[15] = 1.0;
  4707. result._markAsUpdated();
  4708. return this;
  4709. };
  4710. /**
  4711. * Updates the current quaternion from the given rotation matrix values
  4712. * @param matrix defines the source matrix
  4713. * @returns the current updated quaternion
  4714. */
  4715. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4716. Quaternion.FromRotationMatrixToRef(matrix, this);
  4717. return this;
  4718. };
  4719. // Statics
  4720. /**
  4721. * Creates a new quaternion from a rotation matrix
  4722. * @param matrix defines the source matrix
  4723. * @returns a new quaternion created from the given rotation matrix values
  4724. */
  4725. Quaternion.FromRotationMatrix = function (matrix) {
  4726. var result = new Quaternion();
  4727. Quaternion.FromRotationMatrixToRef(matrix, result);
  4728. return result;
  4729. };
  4730. /**
  4731. * Updates the given quaternion with the given rotation matrix values
  4732. * @param matrix defines the source matrix
  4733. * @param result defines the target quaternion
  4734. */
  4735. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4736. var data = matrix.m;
  4737. var m11 = data[0], m12 = data[4], m13 = data[8];
  4738. var m21 = data[1], m22 = data[5], m23 = data[9];
  4739. var m31 = data[2], m32 = data[6], m33 = data[10];
  4740. var trace = m11 + m22 + m33;
  4741. var s;
  4742. if (trace > 0) {
  4743. s = 0.5 / Math.sqrt(trace + 1.0);
  4744. result.w = 0.25 / s;
  4745. result.x = (m32 - m23) * s;
  4746. result.y = (m13 - m31) * s;
  4747. result.z = (m21 - m12) * s;
  4748. }
  4749. else if (m11 > m22 && m11 > m33) {
  4750. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4751. result.w = (m32 - m23) / s;
  4752. result.x = 0.25 * s;
  4753. result.y = (m12 + m21) / s;
  4754. result.z = (m13 + m31) / s;
  4755. }
  4756. else if (m22 > m33) {
  4757. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4758. result.w = (m13 - m31) / s;
  4759. result.x = (m12 + m21) / s;
  4760. result.y = 0.25 * s;
  4761. result.z = (m23 + m32) / s;
  4762. }
  4763. else {
  4764. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4765. result.w = (m21 - m12) / s;
  4766. result.x = (m13 + m31) / s;
  4767. result.y = (m23 + m32) / s;
  4768. result.z = 0.25 * s;
  4769. }
  4770. };
  4771. /**
  4772. * Returns the dot product (float) between the quaternions "left" and "right"
  4773. * @param left defines the left operand
  4774. * @param right defines the right operand
  4775. * @returns the dot product
  4776. */
  4777. Quaternion.Dot = function (left, right) {
  4778. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4779. };
  4780. /**
  4781. * Checks if the two quaternions are close to each other
  4782. * @param quat0 defines the first quaternion to check
  4783. * @param quat1 defines the second quaternion to check
  4784. * @returns true if the two quaternions are close to each other
  4785. */
  4786. Quaternion.AreClose = function (quat0, quat1) {
  4787. var dot = Quaternion.Dot(quat0, quat1);
  4788. return dot >= 0;
  4789. };
  4790. /**
  4791. * Creates an empty quaternion
  4792. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4793. */
  4794. Quaternion.Zero = function () {
  4795. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4796. };
  4797. /**
  4798. * Inverse a given quaternion
  4799. * @param q defines the source quaternion
  4800. * @returns a new quaternion as the inverted current quaternion
  4801. */
  4802. Quaternion.Inverse = function (q) {
  4803. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4804. };
  4805. /**
  4806. * Creates an identity quaternion
  4807. * @returns the identity quaternion
  4808. */
  4809. Quaternion.Identity = function () {
  4810. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4811. };
  4812. /**
  4813. * Gets a boolean indicating if the given quaternion is identity
  4814. * @param quaternion defines the quaternion to check
  4815. * @returns true if the quaternion is identity
  4816. */
  4817. Quaternion.IsIdentity = function (quaternion) {
  4818. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4819. };
  4820. /**
  4821. * Creates a quaternion from a rotation around an axis
  4822. * @param axis defines the axis to use
  4823. * @param angle defines the angle to use
  4824. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4825. */
  4826. Quaternion.RotationAxis = function (axis, angle) {
  4827. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4828. };
  4829. /**
  4830. * Creates a rotation around an axis and stores it into the given quaternion
  4831. * @param axis defines the axis to use
  4832. * @param angle defines the angle to use
  4833. * @param result defines the target quaternion
  4834. * @returns the target quaternion
  4835. */
  4836. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4837. var sin = Math.sin(angle / 2);
  4838. axis.normalize();
  4839. result.w = Math.cos(angle / 2);
  4840. result.x = axis.x * sin;
  4841. result.y = axis.y * sin;
  4842. result.z = axis.z * sin;
  4843. return result;
  4844. };
  4845. /**
  4846. * Creates a new quaternion from data stored into an array
  4847. * @param array defines the data source
  4848. * @param offset defines the offset in the source array where the data starts
  4849. * @returns a new quaternion
  4850. */
  4851. Quaternion.FromArray = function (array, offset) {
  4852. if (!offset) {
  4853. offset = 0;
  4854. }
  4855. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4856. };
  4857. /**
  4858. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4859. * @param yaw defines the rotation around Y axis
  4860. * @param pitch defines the rotation around X axis
  4861. * @param roll defines the rotation around Z axis
  4862. * @returns the new quaternion
  4863. */
  4864. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4865. var q = new Quaternion();
  4866. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4867. return q;
  4868. };
  4869. /**
  4870. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4871. * @param yaw defines the rotation around Y axis
  4872. * @param pitch defines the rotation around X axis
  4873. * @param roll defines the rotation around Z axis
  4874. * @param result defines the target quaternion
  4875. */
  4876. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4877. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4878. var halfRoll = roll * 0.5;
  4879. var halfPitch = pitch * 0.5;
  4880. var halfYaw = yaw * 0.5;
  4881. var sinRoll = Math.sin(halfRoll);
  4882. var cosRoll = Math.cos(halfRoll);
  4883. var sinPitch = Math.sin(halfPitch);
  4884. var cosPitch = Math.cos(halfPitch);
  4885. var sinYaw = Math.sin(halfYaw);
  4886. var cosYaw = Math.cos(halfYaw);
  4887. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4888. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4889. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4890. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4891. };
  4892. /**
  4893. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4894. * @param alpha defines the rotation around first axis
  4895. * @param beta defines the rotation around second axis
  4896. * @param gamma defines the rotation around third axis
  4897. * @returns the new quaternion
  4898. */
  4899. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4900. var result = new Quaternion();
  4901. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4902. return result;
  4903. };
  4904. /**
  4905. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4906. * @param alpha defines the rotation around first axis
  4907. * @param beta defines the rotation around second axis
  4908. * @param gamma defines the rotation around third axis
  4909. * @param result defines the target quaternion
  4910. */
  4911. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4912. // Produces a quaternion from Euler angles in the z-x-z orientation
  4913. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4914. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4915. var halfBeta = beta * 0.5;
  4916. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4917. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4918. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4919. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4920. };
  4921. /**
  4922. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4923. * @param axis1 defines the first axis
  4924. * @param axis2 defines the second axis
  4925. * @param axis3 defines the third axis
  4926. * @returns the new quaternion
  4927. */
  4928. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4929. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4930. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4931. return quat;
  4932. };
  4933. /**
  4934. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4935. * @param axis1 defines the first axis
  4936. * @param axis2 defines the second axis
  4937. * @param axis3 defines the third axis
  4938. * @param ref defines the target quaternion
  4939. */
  4940. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4941. var rotMat = MathTmp.Matrix[0];
  4942. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4943. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4944. };
  4945. /**
  4946. * Interpolates between two quaternions
  4947. * @param left defines first quaternion
  4948. * @param right defines second quaternion
  4949. * @param amount defines the gradient to use
  4950. * @returns the new interpolated quaternion
  4951. */
  4952. Quaternion.Slerp = function (left, right, amount) {
  4953. var result = Quaternion.Identity();
  4954. Quaternion.SlerpToRef(left, right, amount, result);
  4955. return result;
  4956. };
  4957. /**
  4958. * Interpolates between two quaternions and stores it into a target quaternion
  4959. * @param left defines first quaternion
  4960. * @param right defines second quaternion
  4961. * @param amount defines the gradient to use
  4962. * @param result defines the target quaternion
  4963. */
  4964. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4965. var num2;
  4966. var num3;
  4967. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4968. var flag = false;
  4969. if (num4 < 0) {
  4970. flag = true;
  4971. num4 = -num4;
  4972. }
  4973. if (num4 > 0.999999) {
  4974. num3 = 1 - amount;
  4975. num2 = flag ? -amount : amount;
  4976. }
  4977. else {
  4978. var num5 = Math.acos(num4);
  4979. var num6 = (1.0 / Math.sin(num5));
  4980. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4981. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4982. }
  4983. result.x = (num3 * left.x) + (num2 * right.x);
  4984. result.y = (num3 * left.y) + (num2 * right.y);
  4985. result.z = (num3 * left.z) + (num2 * right.z);
  4986. result.w = (num3 * left.w) + (num2 * right.w);
  4987. };
  4988. /**
  4989. * Interpolate between two quaternions using Hermite interpolation
  4990. * @param value1 defines first quaternion
  4991. * @param tangent1 defines the incoming tangent
  4992. * @param value2 defines second quaternion
  4993. * @param tangent2 defines the outgoing tangent
  4994. * @param amount defines the target quaternion
  4995. * @returns the new interpolated quaternion
  4996. */
  4997. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4998. var squared = amount * amount;
  4999. var cubed = amount * squared;
  5000. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5001. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5002. var part3 = (cubed - (2.0 * squared)) + amount;
  5003. var part4 = cubed - squared;
  5004. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5005. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5006. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5007. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5008. return new Quaternion(x, y, z, w);
  5009. };
  5010. return Quaternion;
  5011. }());
  5012. BABYLON.Quaternion = Quaternion;
  5013. /**
  5014. * Class used to store matrix data (4x4)
  5015. */
  5016. var Matrix = /** @class */ (function () {
  5017. /**
  5018. * Creates an empty matrix (filled with zeros)
  5019. */
  5020. function Matrix() {
  5021. this._isIdentity = false;
  5022. this._isIdentityDirty = true;
  5023. /**
  5024. * Gets or sets the internal data of the matrix
  5025. */
  5026. this.m = new Float32Array(16);
  5027. this._markAsUpdated();
  5028. }
  5029. /** @hidden */
  5030. Matrix.prototype._markAsUpdated = function () {
  5031. this.updateFlag = Matrix._updateFlagSeed++;
  5032. this._isIdentityDirty = true;
  5033. };
  5034. // Properties
  5035. /**
  5036. * Check if the current matrix is indentity
  5037. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5038. * @returns true is the matrix is the identity matrix
  5039. */
  5040. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5041. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5042. if (this._isIdentityDirty) {
  5043. this._isIdentityDirty = false;
  5044. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5045. this._isIdentity = false;
  5046. }
  5047. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5048. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5049. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5050. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5051. this._isIdentity = false;
  5052. }
  5053. else {
  5054. this._isIdentity = true;
  5055. }
  5056. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5057. this._isIdentity = false;
  5058. }
  5059. }
  5060. return this._isIdentity;
  5061. };
  5062. /**
  5063. * Gets the determinant of the matrix
  5064. * @returns the matrix determinant
  5065. */
  5066. Matrix.prototype.determinant = function () {
  5067. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5068. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5069. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5070. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5071. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5072. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5073. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5074. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5075. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5076. };
  5077. // Methods
  5078. /**
  5079. * Returns the matrix as a Float32Array
  5080. * @returns the matrix underlying array
  5081. */
  5082. Matrix.prototype.toArray = function () {
  5083. return this.m;
  5084. };
  5085. /**
  5086. * Returns the matrix as a Float32Array
  5087. * @returns the matrix underlying array.
  5088. */
  5089. Matrix.prototype.asArray = function () {
  5090. return this.toArray();
  5091. };
  5092. /**
  5093. * Inverts the current matrix in place
  5094. * @returns the current inverted matrix
  5095. */
  5096. Matrix.prototype.invert = function () {
  5097. this.invertToRef(this);
  5098. return this;
  5099. };
  5100. /**
  5101. * Sets all the matrix elements to zero
  5102. * @returns the current matrix
  5103. */
  5104. Matrix.prototype.reset = function () {
  5105. for (var index = 0; index < 16; index++) {
  5106. this.m[index] = 0.0;
  5107. }
  5108. this._markAsUpdated();
  5109. return this;
  5110. };
  5111. /**
  5112. * Adds the current matrix with a second one
  5113. * @param other defines the matrix to add
  5114. * @returns a new matrix as the addition of the current matrix and the given one
  5115. */
  5116. Matrix.prototype.add = function (other) {
  5117. var result = new Matrix();
  5118. this.addToRef(other, result);
  5119. return result;
  5120. };
  5121. /**
  5122. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5123. * @param other defines the matrix to add
  5124. * @param result defines the target matrix
  5125. * @returns the current matrix
  5126. */
  5127. Matrix.prototype.addToRef = function (other, result) {
  5128. for (var index = 0; index < 16; index++) {
  5129. result.m[index] = this.m[index] + other.m[index];
  5130. }
  5131. result._markAsUpdated();
  5132. return this;
  5133. };
  5134. /**
  5135. * Adds in place the given matrix to the current matrix
  5136. * @param other defines the second operand
  5137. * @returns the current updated matrix
  5138. */
  5139. Matrix.prototype.addToSelf = function (other) {
  5140. for (var index = 0; index < 16; index++) {
  5141. this.m[index] += other.m[index];
  5142. }
  5143. this._markAsUpdated();
  5144. return this;
  5145. };
  5146. /**
  5147. * Sets the given matrix to the current inverted Matrix
  5148. * @param other defines the target matrix
  5149. * @returns the unmodified current matrix
  5150. */
  5151. Matrix.prototype.invertToRef = function (other) {
  5152. var l1 = this.m[0];
  5153. var l2 = this.m[1];
  5154. var l3 = this.m[2];
  5155. var l4 = this.m[3];
  5156. var l5 = this.m[4];
  5157. var l6 = this.m[5];
  5158. var l7 = this.m[6];
  5159. var l8 = this.m[7];
  5160. var l9 = this.m[8];
  5161. var l10 = this.m[9];
  5162. var l11 = this.m[10];
  5163. var l12 = this.m[11];
  5164. var l13 = this.m[12];
  5165. var l14 = this.m[13];
  5166. var l15 = this.m[14];
  5167. var l16 = this.m[15];
  5168. var l17 = (l11 * l16) - (l12 * l15);
  5169. var l18 = (l10 * l16) - (l12 * l14);
  5170. var l19 = (l10 * l15) - (l11 * l14);
  5171. var l20 = (l9 * l16) - (l12 * l13);
  5172. var l21 = (l9 * l15) - (l11 * l13);
  5173. var l22 = (l9 * l14) - (l10 * l13);
  5174. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5175. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5176. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5177. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5178. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5179. var l28 = (l7 * l16) - (l8 * l15);
  5180. var l29 = (l6 * l16) - (l8 * l14);
  5181. var l30 = (l6 * l15) - (l7 * l14);
  5182. var l31 = (l5 * l16) - (l8 * l13);
  5183. var l32 = (l5 * l15) - (l7 * l13);
  5184. var l33 = (l5 * l14) - (l6 * l13);
  5185. var l34 = (l7 * l12) - (l8 * l11);
  5186. var l35 = (l6 * l12) - (l8 * l10);
  5187. var l36 = (l6 * l11) - (l7 * l10);
  5188. var l37 = (l5 * l12) - (l8 * l9);
  5189. var l38 = (l5 * l11) - (l7 * l9);
  5190. var l39 = (l5 * l10) - (l6 * l9);
  5191. other.m[0] = l23 * l27;
  5192. other.m[4] = l24 * l27;
  5193. other.m[8] = l25 * l27;
  5194. other.m[12] = l26 * l27;
  5195. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5196. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5197. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5198. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5199. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5200. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5201. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5202. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5203. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5204. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5205. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5206. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5207. other._markAsUpdated();
  5208. return this;
  5209. };
  5210. /**
  5211. * Inserts the translation vector (using 3 floats) in the current matrix
  5212. * @param x defines the 1st component of the translation
  5213. * @param y defines the 2nd component of the translation
  5214. * @param z defines the 3rd component of the translation
  5215. * @returns the current updated matrix
  5216. */
  5217. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5218. this.m[12] = x;
  5219. this.m[13] = y;
  5220. this.m[14] = z;
  5221. this._markAsUpdated();
  5222. return this;
  5223. };
  5224. /**
  5225. * Inserts the translation vector in the current matrix
  5226. * @param vector3 defines the translation to insert
  5227. * @returns the current updated matrix
  5228. */
  5229. Matrix.prototype.setTranslation = function (vector3) {
  5230. this.m[12] = vector3.x;
  5231. this.m[13] = vector3.y;
  5232. this.m[14] = vector3.z;
  5233. this._markAsUpdated();
  5234. return this;
  5235. };
  5236. /**
  5237. * Gets the translation value of the current matrix
  5238. * @returns a new Vector3 as the extracted translation from the matrix
  5239. */
  5240. Matrix.prototype.getTranslation = function () {
  5241. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5242. };
  5243. /**
  5244. * Fill a Vector3 with the extracted translation from the matrix
  5245. * @param result defines the Vector3 where to store the translation
  5246. * @returns the current matrix
  5247. */
  5248. Matrix.prototype.getTranslationToRef = function (result) {
  5249. result.x = this.m[12];
  5250. result.y = this.m[13];
  5251. result.z = this.m[14];
  5252. return this;
  5253. };
  5254. /**
  5255. * Remove rotation and scaling part from the matrix
  5256. * @returns the updated matrix
  5257. */
  5258. Matrix.prototype.removeRotationAndScaling = function () {
  5259. this.setRowFromFloats(0, 1, 0, 0, 0);
  5260. this.setRowFromFloats(1, 0, 1, 0, 0);
  5261. this.setRowFromFloats(2, 0, 0, 1, 0);
  5262. return this;
  5263. };
  5264. /**
  5265. * Multiply two matrices
  5266. * @param other defines the second operand
  5267. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5268. */
  5269. Matrix.prototype.multiply = function (other) {
  5270. var result = new Matrix();
  5271. this.multiplyToRef(other, result);
  5272. return result;
  5273. };
  5274. /**
  5275. * Copy the current matrix from the given one
  5276. * @param other defines the source matrix
  5277. * @returns the current updated matrix
  5278. */
  5279. Matrix.prototype.copyFrom = function (other) {
  5280. for (var index = 0; index < 16; index++) {
  5281. this.m[index] = other.m[index];
  5282. }
  5283. this._markAsUpdated();
  5284. return this;
  5285. };
  5286. /**
  5287. * Populates the given array from the starting index with the current matrix values
  5288. * @param array defines the target array
  5289. * @param offset defines the offset in the target array where to start storing values
  5290. * @returns the current matrix
  5291. */
  5292. Matrix.prototype.copyToArray = function (array, offset) {
  5293. if (offset === void 0) { offset = 0; }
  5294. for (var index = 0; index < 16; index++) {
  5295. array[offset + index] = this.m[index];
  5296. }
  5297. return this;
  5298. };
  5299. /**
  5300. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5301. * @param other defines the second operand
  5302. * @param result defines the matrix where to store the multiplication
  5303. * @returns the current matrix
  5304. */
  5305. Matrix.prototype.multiplyToRef = function (other, result) {
  5306. this.multiplyToArray(other, result.m, 0);
  5307. result._markAsUpdated();
  5308. return this;
  5309. };
  5310. /**
  5311. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5312. * @param other defines the second operand
  5313. * @param result defines the array where to store the multiplication
  5314. * @param offset defines the offset in the target array where to start storing values
  5315. * @returns the current matrix
  5316. */
  5317. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5318. var tm0 = this.m[0];
  5319. var tm1 = this.m[1];
  5320. var tm2 = this.m[2];
  5321. var tm3 = this.m[3];
  5322. var tm4 = this.m[4];
  5323. var tm5 = this.m[5];
  5324. var tm6 = this.m[6];
  5325. var tm7 = this.m[7];
  5326. var tm8 = this.m[8];
  5327. var tm9 = this.m[9];
  5328. var tm10 = this.m[10];
  5329. var tm11 = this.m[11];
  5330. var tm12 = this.m[12];
  5331. var tm13 = this.m[13];
  5332. var tm14 = this.m[14];
  5333. var tm15 = this.m[15];
  5334. var om0 = other.m[0];
  5335. var om1 = other.m[1];
  5336. var om2 = other.m[2];
  5337. var om3 = other.m[3];
  5338. var om4 = other.m[4];
  5339. var om5 = other.m[5];
  5340. var om6 = other.m[6];
  5341. var om7 = other.m[7];
  5342. var om8 = other.m[8];
  5343. var om9 = other.m[9];
  5344. var om10 = other.m[10];
  5345. var om11 = other.m[11];
  5346. var om12 = other.m[12];
  5347. var om13 = other.m[13];
  5348. var om14 = other.m[14];
  5349. var om15 = other.m[15];
  5350. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5351. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5352. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5353. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5354. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5355. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5356. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5357. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5358. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5359. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5360. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5361. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5362. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5363. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5364. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5365. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5366. return this;
  5367. };
  5368. /**
  5369. * Check equality between this matrix and a second one
  5370. * @param value defines the second matrix to compare
  5371. * @returns true is the current matrix and the given one values are strictly equal
  5372. */
  5373. Matrix.prototype.equals = function (value) {
  5374. return value &&
  5375. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5376. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5377. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5378. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5379. };
  5380. /**
  5381. * Clone the current matrix
  5382. * @returns a new matrix from the current matrix
  5383. */
  5384. Matrix.prototype.clone = function () {
  5385. 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]);
  5386. };
  5387. /**
  5388. * Returns the name of the current matrix class
  5389. * @returns the string "Matrix"
  5390. */
  5391. Matrix.prototype.getClassName = function () {
  5392. return "Matrix";
  5393. };
  5394. /**
  5395. * Gets the hash code of the current matrix
  5396. * @returns the hash code
  5397. */
  5398. Matrix.prototype.getHashCode = function () {
  5399. var hash = this.m[0] || 0;
  5400. for (var i = 1; i < 16; i++) {
  5401. hash = (hash * 397) ^ (this.m[i] || 0);
  5402. }
  5403. return hash;
  5404. };
  5405. /**
  5406. * Decomposes the current Matrix into a translation, rotation and scaling components
  5407. * @param scale defines the scale vector3 given as a reference to update
  5408. * @param rotation defines the rotation quaternion given as a reference to update
  5409. * @param translation defines the translation vector3 given as a reference to update
  5410. * @returns true if operation was successful
  5411. */
  5412. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5413. if (translation) {
  5414. translation.x = this.m[12];
  5415. translation.y = this.m[13];
  5416. translation.z = this.m[14];
  5417. }
  5418. scale = scale || MathTmp.Vector3[0];
  5419. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5420. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5421. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5422. if (this.determinant() <= 0) {
  5423. scale.y *= -1;
  5424. }
  5425. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5426. if (rotation) {
  5427. rotation.x = 0;
  5428. rotation.y = 0;
  5429. rotation.z = 0;
  5430. rotation.w = 1;
  5431. }
  5432. return false;
  5433. }
  5434. if (rotation) {
  5435. 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]);
  5436. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5437. }
  5438. return true;
  5439. };
  5440. /**
  5441. * Gets specific row of the matrix
  5442. * @param index defines the number of the row to get
  5443. * @returns the index-th row of the current matrix as a new Vector4
  5444. */
  5445. Matrix.prototype.getRow = function (index) {
  5446. if (index < 0 || index > 3) {
  5447. return null;
  5448. }
  5449. var i = index * 4;
  5450. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5451. };
  5452. /**
  5453. * Sets the index-th row of the current matrix to the vector4 values
  5454. * @param index defines the number of the row to set
  5455. * @param row defines the target vector4
  5456. * @returns the updated current matrix
  5457. */
  5458. Matrix.prototype.setRow = function (index, row) {
  5459. if (index < 0 || index > 3) {
  5460. return this;
  5461. }
  5462. var i = index * 4;
  5463. this.m[i + 0] = row.x;
  5464. this.m[i + 1] = row.y;
  5465. this.m[i + 2] = row.z;
  5466. this.m[i + 3] = row.w;
  5467. this._markAsUpdated();
  5468. return this;
  5469. };
  5470. /**
  5471. * Compute the transpose of the matrix
  5472. * @returns the new transposed matrix
  5473. */
  5474. Matrix.prototype.transpose = function () {
  5475. return Matrix.Transpose(this);
  5476. };
  5477. /**
  5478. * Compute the transpose of the matrix and store it in a given matrix
  5479. * @param result defines the target matrix
  5480. * @returns the current matrix
  5481. */
  5482. Matrix.prototype.transposeToRef = function (result) {
  5483. Matrix.TransposeToRef(this, result);
  5484. return this;
  5485. };
  5486. /**
  5487. * Sets the index-th row of the current matrix with the given 4 x float values
  5488. * @param index defines the row index
  5489. * @param x defines the x component to set
  5490. * @param y defines the y component to set
  5491. * @param z defines the z component to set
  5492. * @param w defines the w component to set
  5493. * @returns the updated current matrix
  5494. */
  5495. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5496. if (index < 0 || index > 3) {
  5497. return this;
  5498. }
  5499. var i = index * 4;
  5500. this.m[i + 0] = x;
  5501. this.m[i + 1] = y;
  5502. this.m[i + 2] = z;
  5503. this.m[i + 3] = w;
  5504. this._markAsUpdated();
  5505. return this;
  5506. };
  5507. /**
  5508. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5509. * @param scale defines the scale factor
  5510. * @returns a new matrix
  5511. */
  5512. Matrix.prototype.scale = function (scale) {
  5513. var result = new Matrix();
  5514. this.scaleToRef(scale, result);
  5515. return result;
  5516. };
  5517. /**
  5518. * Scale the current matrix values by a factor to a given result matrix
  5519. * @param scale defines the scale factor
  5520. * @param result defines the matrix to store the result
  5521. * @returns the current matrix
  5522. */
  5523. Matrix.prototype.scaleToRef = function (scale, result) {
  5524. for (var index = 0; index < 16; index++) {
  5525. result.m[index] = this.m[index] * scale;
  5526. }
  5527. result._markAsUpdated();
  5528. return this;
  5529. };
  5530. /**
  5531. * Scale the current matrix values by a factor and add the result to a given matrix
  5532. * @param scale defines the scale factor
  5533. * @param result defines the Matrix to store the result
  5534. * @returns the current matrix
  5535. */
  5536. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5537. for (var index = 0; index < 16; index++) {
  5538. result.m[index] += this.m[index] * scale;
  5539. }
  5540. result._markAsUpdated();
  5541. return this;
  5542. };
  5543. /**
  5544. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5545. * @param ref matrix to store the result
  5546. */
  5547. Matrix.prototype.toNormalMatrix = function (ref) {
  5548. this.invertToRef(ref);
  5549. ref.transpose();
  5550. var m = ref.m;
  5551. 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);
  5552. };
  5553. /**
  5554. * Gets only rotation part of the current matrix
  5555. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5556. */
  5557. Matrix.prototype.getRotationMatrix = function () {
  5558. var result = Matrix.Identity();
  5559. this.getRotationMatrixToRef(result);
  5560. return result;
  5561. };
  5562. /**
  5563. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5564. * @param result defines the target matrix to store data to
  5565. * @returns the current matrix
  5566. */
  5567. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5568. var m = this.m;
  5569. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5570. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5571. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5572. if (this.determinant() <= 0) {
  5573. sy *= -1;
  5574. }
  5575. if (sx === 0 || sy === 0 || sz === 0) {
  5576. Matrix.IdentityToRef(result);
  5577. }
  5578. else {
  5579. 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);
  5580. }
  5581. return this;
  5582. };
  5583. // Statics
  5584. /**
  5585. * Creates a matrix from an array
  5586. * @param array defines the source array
  5587. * @param offset defines an offset in the source array
  5588. * @returns a new Matrix set from the starting index of the given array
  5589. */
  5590. Matrix.FromArray = function (array, offset) {
  5591. var result = new Matrix();
  5592. if (!offset) {
  5593. offset = 0;
  5594. }
  5595. Matrix.FromArrayToRef(array, offset, result);
  5596. return result;
  5597. };
  5598. /**
  5599. * Copy the content of an array into a given matrix
  5600. * @param array defines the source array
  5601. * @param offset defines an offset in the source array
  5602. * @param result defines the target matrix
  5603. */
  5604. Matrix.FromArrayToRef = function (array, offset, result) {
  5605. for (var index = 0; index < 16; index++) {
  5606. result.m[index] = array[index + offset];
  5607. }
  5608. result._markAsUpdated();
  5609. };
  5610. /**
  5611. * Stores an array into a matrix after having multiplied each component by a given factor
  5612. * @param array defines the source array
  5613. * @param offset defines the offset in the source array
  5614. * @param scale defines the scaling factor
  5615. * @param result defines the target matrix
  5616. */
  5617. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5618. for (var index = 0; index < 16; index++) {
  5619. result.m[index] = array[index + offset] * scale;
  5620. }
  5621. result._markAsUpdated();
  5622. };
  5623. /**
  5624. * Stores a list of values (16) inside a given matrix
  5625. * @param initialM11 defines 1st value of 1st row
  5626. * @param initialM12 defines 2nd value of 1st row
  5627. * @param initialM13 defines 3rd value of 1st row
  5628. * @param initialM14 defines 4th value of 1st row
  5629. * @param initialM21 defines 1st value of 2nd row
  5630. * @param initialM22 defines 2nd value of 2nd row
  5631. * @param initialM23 defines 3rd value of 2nd row
  5632. * @param initialM24 defines 4th value of 2nd row
  5633. * @param initialM31 defines 1st value of 3rd row
  5634. * @param initialM32 defines 2nd value of 3rd row
  5635. * @param initialM33 defines 3rd value of 3rd row
  5636. * @param initialM34 defines 4th value of 3rd row
  5637. * @param initialM41 defines 1st value of 4th row
  5638. * @param initialM42 defines 2nd value of 4th row
  5639. * @param initialM43 defines 3rd value of 4th row
  5640. * @param initialM44 defines 4th value of 4th row
  5641. * @param result defines the target matrix
  5642. */
  5643. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5644. result.m[0] = initialM11;
  5645. result.m[1] = initialM12;
  5646. result.m[2] = initialM13;
  5647. result.m[3] = initialM14;
  5648. result.m[4] = initialM21;
  5649. result.m[5] = initialM22;
  5650. result.m[6] = initialM23;
  5651. result.m[7] = initialM24;
  5652. result.m[8] = initialM31;
  5653. result.m[9] = initialM32;
  5654. result.m[10] = initialM33;
  5655. result.m[11] = initialM34;
  5656. result.m[12] = initialM41;
  5657. result.m[13] = initialM42;
  5658. result.m[14] = initialM43;
  5659. result.m[15] = initialM44;
  5660. result._markAsUpdated();
  5661. };
  5662. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5663. /**
  5664. * Gets an identity matrix that must not be updated
  5665. */
  5666. get: function () {
  5667. return Matrix._identityReadOnly;
  5668. },
  5669. enumerable: true,
  5670. configurable: true
  5671. });
  5672. /**
  5673. * Creates new matrix from a list of values (16)
  5674. * @param initialM11 defines 1st value of 1st row
  5675. * @param initialM12 defines 2nd value of 1st row
  5676. * @param initialM13 defines 3rd value of 1st row
  5677. * @param initialM14 defines 4th value of 1st row
  5678. * @param initialM21 defines 1st value of 2nd row
  5679. * @param initialM22 defines 2nd value of 2nd row
  5680. * @param initialM23 defines 3rd value of 2nd row
  5681. * @param initialM24 defines 4th value of 2nd row
  5682. * @param initialM31 defines 1st value of 3rd row
  5683. * @param initialM32 defines 2nd value of 3rd row
  5684. * @param initialM33 defines 3rd value of 3rd row
  5685. * @param initialM34 defines 4th value of 3rd row
  5686. * @param initialM41 defines 1st value of 4th row
  5687. * @param initialM42 defines 2nd value of 4th row
  5688. * @param initialM43 defines 3rd value of 4th row
  5689. * @param initialM44 defines 4th value of 4th row
  5690. * @returns the new matrix
  5691. */
  5692. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5693. var result = new Matrix();
  5694. result.m[0] = initialM11;
  5695. result.m[1] = initialM12;
  5696. result.m[2] = initialM13;
  5697. result.m[3] = initialM14;
  5698. result.m[4] = initialM21;
  5699. result.m[5] = initialM22;
  5700. result.m[6] = initialM23;
  5701. result.m[7] = initialM24;
  5702. result.m[8] = initialM31;
  5703. result.m[9] = initialM32;
  5704. result.m[10] = initialM33;
  5705. result.m[11] = initialM34;
  5706. result.m[12] = initialM41;
  5707. result.m[13] = initialM42;
  5708. result.m[14] = initialM43;
  5709. result.m[15] = initialM44;
  5710. return result;
  5711. };
  5712. /**
  5713. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5714. * @param scale defines the scale vector3
  5715. * @param rotation defines the rotation quaternion
  5716. * @param translation defines the translation vector3
  5717. * @returns a new matrix
  5718. */
  5719. Matrix.Compose = function (scale, rotation, translation) {
  5720. var result = Matrix.Identity();
  5721. Matrix.ComposeToRef(scale, rotation, translation, result);
  5722. return result;
  5723. };
  5724. /**
  5725. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5726. * @param scale defines the scale vector3
  5727. * @param rotation defines the rotation quaternion
  5728. * @param translation defines the translation vector3
  5729. * @param result defines the target matrix
  5730. */
  5731. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5732. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5733. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5734. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5735. result.setTranslation(translation);
  5736. };
  5737. /**
  5738. * Creates a new identity matrix
  5739. * @returns a new identity matrix
  5740. */
  5741. Matrix.Identity = function () {
  5742. 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);
  5743. };
  5744. /**
  5745. * Creates a new identity matrix and stores the result in a given matrix
  5746. * @param result defines the target matrix
  5747. */
  5748. Matrix.IdentityToRef = function (result) {
  5749. 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);
  5750. };
  5751. /**
  5752. * Creates a new zero matrix
  5753. * @returns a new zero matrix
  5754. */
  5755. Matrix.Zero = function () {
  5756. 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);
  5757. };
  5758. /**
  5759. * Creates a new rotation matrix for "angle" radians around the X axis
  5760. * @param angle defines the angle (in radians) to use
  5761. * @return the new matrix
  5762. */
  5763. Matrix.RotationX = function (angle) {
  5764. var result = new Matrix();
  5765. Matrix.RotationXToRef(angle, result);
  5766. return result;
  5767. };
  5768. /**
  5769. * Creates a new matrix as the invert of a given matrix
  5770. * @param source defines the source matrix
  5771. * @returns the new matrix
  5772. */
  5773. Matrix.Invert = function (source) {
  5774. var result = new Matrix();
  5775. source.invertToRef(result);
  5776. return result;
  5777. };
  5778. /**
  5779. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5780. * @param angle defines the angle (in radians) to use
  5781. * @param result defines the target matrix
  5782. */
  5783. Matrix.RotationXToRef = function (angle, result) {
  5784. var s = Math.sin(angle);
  5785. var c = Math.cos(angle);
  5786. result.m[0] = 1.0;
  5787. result.m[15] = 1.0;
  5788. result.m[5] = c;
  5789. result.m[10] = c;
  5790. result.m[9] = -s;
  5791. result.m[6] = s;
  5792. result.m[1] = 0.0;
  5793. result.m[2] = 0.0;
  5794. result.m[3] = 0.0;
  5795. result.m[4] = 0.0;
  5796. result.m[7] = 0.0;
  5797. result.m[8] = 0.0;
  5798. result.m[11] = 0.0;
  5799. result.m[12] = 0.0;
  5800. result.m[13] = 0.0;
  5801. result.m[14] = 0.0;
  5802. result._markAsUpdated();
  5803. };
  5804. /**
  5805. * Creates a new rotation matrix for "angle" radians around the Y axis
  5806. * @param angle defines the angle (in radians) to use
  5807. * @return the new matrix
  5808. */
  5809. Matrix.RotationY = function (angle) {
  5810. var result = new Matrix();
  5811. Matrix.RotationYToRef(angle, result);
  5812. return result;
  5813. };
  5814. /**
  5815. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5816. * @param angle defines the angle (in radians) to use
  5817. * @param result defines the target matrix
  5818. */
  5819. Matrix.RotationYToRef = function (angle, result) {
  5820. var s = Math.sin(angle);
  5821. var c = Math.cos(angle);
  5822. result.m[5] = 1.0;
  5823. result.m[15] = 1.0;
  5824. result.m[0] = c;
  5825. result.m[2] = -s;
  5826. result.m[8] = s;
  5827. result.m[10] = c;
  5828. result.m[1] = 0.0;
  5829. result.m[3] = 0.0;
  5830. result.m[4] = 0.0;
  5831. result.m[6] = 0.0;
  5832. result.m[7] = 0.0;
  5833. result.m[9] = 0.0;
  5834. result.m[11] = 0.0;
  5835. result.m[12] = 0.0;
  5836. result.m[13] = 0.0;
  5837. result.m[14] = 0.0;
  5838. result._markAsUpdated();
  5839. };
  5840. /**
  5841. * Creates a new rotation matrix for "angle" radians around the Z axis
  5842. * @param angle defines the angle (in radians) to use
  5843. * @return the new matrix
  5844. */
  5845. Matrix.RotationZ = function (angle) {
  5846. var result = new Matrix();
  5847. Matrix.RotationZToRef(angle, result);
  5848. return result;
  5849. };
  5850. /**
  5851. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5852. * @param angle defines the angle (in radians) to use
  5853. * @param result defines the target matrix
  5854. */
  5855. Matrix.RotationZToRef = function (angle, result) {
  5856. var s = Math.sin(angle);
  5857. var c = Math.cos(angle);
  5858. result.m[10] = 1.0;
  5859. result.m[15] = 1.0;
  5860. result.m[0] = c;
  5861. result.m[1] = s;
  5862. result.m[4] = -s;
  5863. result.m[5] = c;
  5864. result.m[2] = 0.0;
  5865. result.m[3] = 0.0;
  5866. result.m[6] = 0.0;
  5867. result.m[7] = 0.0;
  5868. result.m[8] = 0.0;
  5869. result.m[9] = 0.0;
  5870. result.m[11] = 0.0;
  5871. result.m[12] = 0.0;
  5872. result.m[13] = 0.0;
  5873. result.m[14] = 0.0;
  5874. result._markAsUpdated();
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the given axis
  5878. * @param axis defines the axis to use
  5879. * @param angle defines the angle (in radians) to use
  5880. * @return the new matrix
  5881. */
  5882. Matrix.RotationAxis = function (axis, angle) {
  5883. var result = Matrix.Zero();
  5884. Matrix.RotationAxisToRef(axis, angle, result);
  5885. return result;
  5886. };
  5887. /**
  5888. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5889. * @param axis defines the axis to use
  5890. * @param angle defines the angle (in radians) to use
  5891. * @param result defines the target matrix
  5892. */
  5893. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5894. var s = Math.sin(-angle);
  5895. var c = Math.cos(-angle);
  5896. var c1 = 1 - c;
  5897. axis.normalize();
  5898. result.m[0] = (axis.x * axis.x) * c1 + c;
  5899. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5900. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5901. result.m[3] = 0.0;
  5902. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5903. result.m[5] = (axis.y * axis.y) * c1 + c;
  5904. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5905. result.m[7] = 0.0;
  5906. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5907. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5908. result.m[10] = (axis.z * axis.z) * c1 + c;
  5909. result.m[11] = 0.0;
  5910. result.m[15] = 1.0;
  5911. result._markAsUpdated();
  5912. };
  5913. /**
  5914. * Creates a rotation matrix
  5915. * @param yaw defines the yaw angle in radians (Y axis)
  5916. * @param pitch defines the pitch angle in radians (X axis)
  5917. * @param roll defines the roll angle in radians (X axis)
  5918. * @returns the new rotation matrix
  5919. */
  5920. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5921. var result = new Matrix();
  5922. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5923. return result;
  5924. };
  5925. /**
  5926. * Creates a rotation matrix and stores it in a given matrix
  5927. * @param yaw defines the yaw angle in radians (Y axis)
  5928. * @param pitch defines the pitch angle in radians (X axis)
  5929. * @param roll defines the roll angle in radians (X axis)
  5930. * @param result defines the target matrix
  5931. */
  5932. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5933. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5934. this._tempQuaternion.toRotationMatrix(result);
  5935. };
  5936. /**
  5937. * Creates a scaling matrix
  5938. * @param x defines the scale factor on X axis
  5939. * @param y defines the scale factor on Y axis
  5940. * @param z defines the scale factor on Z axis
  5941. * @returns the new matrix
  5942. */
  5943. Matrix.Scaling = function (x, y, z) {
  5944. var result = Matrix.Zero();
  5945. Matrix.ScalingToRef(x, y, z, result);
  5946. return result;
  5947. };
  5948. /**
  5949. * Creates a scaling matrix and stores it in a given matrix
  5950. * @param x defines the scale factor on X axis
  5951. * @param y defines the scale factor on Y axis
  5952. * @param z defines the scale factor on Z axis
  5953. * @param result defines the target matrix
  5954. */
  5955. Matrix.ScalingToRef = function (x, y, z, result) {
  5956. result.m[0] = x;
  5957. result.m[1] = 0.0;
  5958. result.m[2] = 0.0;
  5959. result.m[3] = 0.0;
  5960. result.m[4] = 0.0;
  5961. result.m[5] = y;
  5962. result.m[6] = 0.0;
  5963. result.m[7] = 0.0;
  5964. result.m[8] = 0.0;
  5965. result.m[9] = 0.0;
  5966. result.m[10] = z;
  5967. result.m[11] = 0.0;
  5968. result.m[12] = 0.0;
  5969. result.m[13] = 0.0;
  5970. result.m[14] = 0.0;
  5971. result.m[15] = 1.0;
  5972. result._markAsUpdated();
  5973. };
  5974. /**
  5975. * Creates a translation matrix
  5976. * @param x defines the translation on X axis
  5977. * @param y defines the translation on Y axis
  5978. * @param z defines the translationon Z axis
  5979. * @returns the new matrix
  5980. */
  5981. Matrix.Translation = function (x, y, z) {
  5982. var result = Matrix.Identity();
  5983. Matrix.TranslationToRef(x, y, z, result);
  5984. return result;
  5985. };
  5986. /**
  5987. * Creates a translation matrix and stores it in a given matrix
  5988. * @param x defines the translation on X axis
  5989. * @param y defines the translation on Y axis
  5990. * @param z defines the translationon Z axis
  5991. * @param result defines the target matrix
  5992. */
  5993. Matrix.TranslationToRef = function (x, y, z, result) {
  5994. 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);
  5995. };
  5996. /**
  5997. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5998. * @param startValue defines the start value
  5999. * @param endValue defines the end value
  6000. * @param gradient defines the gradient factor
  6001. * @returns the new matrix
  6002. */
  6003. Matrix.Lerp = function (startValue, endValue, gradient) {
  6004. var result = Matrix.Zero();
  6005. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6006. return result;
  6007. };
  6008. /**
  6009. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6010. * @param startValue defines the start value
  6011. * @param endValue defines the end value
  6012. * @param gradient defines the gradient factor
  6013. * @param result defines the Matrix object where to store data
  6014. */
  6015. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6016. for (var index = 0; index < 16; index++) {
  6017. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6018. }
  6019. result._markAsUpdated();
  6020. };
  6021. /**
  6022. * Builds a new matrix whose values are computed by:
  6023. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6024. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6025. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6026. * @param startValue defines the first matrix
  6027. * @param endValue defines the second matrix
  6028. * @param gradient defines the gradient between the two matrices
  6029. * @returns the new matrix
  6030. */
  6031. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6032. var result = Matrix.Zero();
  6033. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6034. return result;
  6035. };
  6036. /**
  6037. * Update a matrix to values which are computed by:
  6038. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6039. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6040. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6041. * @param startValue defines the first matrix
  6042. * @param endValue defines the second matrix
  6043. * @param gradient defines the gradient between the two matrices
  6044. * @param result defines the target matrix
  6045. */
  6046. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6047. var startScale = MathTmp.Vector3[0];
  6048. var startRotation = MathTmp.Quaternion[0];
  6049. var startTranslation = MathTmp.Vector3[1];
  6050. startValue.decompose(startScale, startRotation, startTranslation);
  6051. var endScale = MathTmp.Vector3[2];
  6052. var endRotation = MathTmp.Quaternion[1];
  6053. var endTranslation = MathTmp.Vector3[3];
  6054. endValue.decompose(endScale, endRotation, endTranslation);
  6055. var resultScale = MathTmp.Vector3[4];
  6056. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6057. var resultRotation = MathTmp.Quaternion[2];
  6058. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6059. var resultTranslation = MathTmp.Vector3[5];
  6060. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6061. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6062. };
  6063. /**
  6064. * 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"
  6065. * This function works in left handed mode
  6066. * @param eye defines the final position of the entity
  6067. * @param target defines where the entity should look at
  6068. * @param up defines the up vector for the entity
  6069. * @returns the new matrix
  6070. */
  6071. Matrix.LookAtLH = function (eye, target, up) {
  6072. var result = Matrix.Zero();
  6073. Matrix.LookAtLHToRef(eye, target, up, result);
  6074. return result;
  6075. };
  6076. /**
  6077. * 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".
  6078. * This function works in left handed mode
  6079. * @param eye defines the final position of the entity
  6080. * @param target defines where the entity should look at
  6081. * @param up defines the up vector for the entity
  6082. * @param result defines the target matrix
  6083. */
  6084. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6085. // Z axis
  6086. target.subtractToRef(eye, this._zAxis);
  6087. this._zAxis.normalize();
  6088. // X axis
  6089. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6090. if (this._xAxis.lengthSquared() === 0) {
  6091. this._xAxis.x = 1.0;
  6092. }
  6093. else {
  6094. this._xAxis.normalize();
  6095. }
  6096. // Y axis
  6097. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6098. this._yAxis.normalize();
  6099. // Eye angles
  6100. var ex = -Vector3.Dot(this._xAxis, eye);
  6101. var ey = -Vector3.Dot(this._yAxis, eye);
  6102. var ez = -Vector3.Dot(this._zAxis, eye);
  6103. 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);
  6104. };
  6105. /**
  6106. * 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"
  6107. * This function works in right handed mode
  6108. * @param eye defines the final position of the entity
  6109. * @param target defines where the entity should look at
  6110. * @param up defines the up vector for the entity
  6111. * @returns the new matrix
  6112. */
  6113. Matrix.LookAtRH = function (eye, target, up) {
  6114. var result = Matrix.Zero();
  6115. Matrix.LookAtRHToRef(eye, target, up, result);
  6116. return result;
  6117. };
  6118. /**
  6119. * 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".
  6120. * This function works in right handed mode
  6121. * @param eye defines the final position of the entity
  6122. * @param target defines where the entity should look at
  6123. * @param up defines the up vector for the entity
  6124. * @param result defines the target matrix
  6125. */
  6126. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6127. // Z axis
  6128. eye.subtractToRef(target, this._zAxis);
  6129. this._zAxis.normalize();
  6130. // X axis
  6131. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6132. if (this._xAxis.lengthSquared() === 0) {
  6133. this._xAxis.x = 1.0;
  6134. }
  6135. else {
  6136. this._xAxis.normalize();
  6137. }
  6138. // Y axis
  6139. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6140. this._yAxis.normalize();
  6141. // Eye angles
  6142. var ex = -Vector3.Dot(this._xAxis, eye);
  6143. var ey = -Vector3.Dot(this._yAxis, eye);
  6144. var ez = -Vector3.Dot(this._zAxis, eye);
  6145. 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);
  6146. };
  6147. /**
  6148. * Create a left-handed orthographic projection matrix
  6149. * @param width defines the viewport width
  6150. * @param height defines the viewport height
  6151. * @param znear defines the near clip plane
  6152. * @param zfar defines the far clip plane
  6153. * @returns a new matrix as a left-handed orthographic projection matrix
  6154. */
  6155. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6156. var matrix = Matrix.Zero();
  6157. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6158. return matrix;
  6159. };
  6160. /**
  6161. * Store a left-handed orthographic projection to a given matrix
  6162. * @param width defines the viewport width
  6163. * @param height defines the viewport height
  6164. * @param znear defines the near clip plane
  6165. * @param zfar defines the far clip plane
  6166. * @param result defines the target matrix
  6167. */
  6168. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6169. var n = znear;
  6170. var f = zfar;
  6171. var a = 2.0 / width;
  6172. var b = 2.0 / height;
  6173. var c = 2.0 / (f - n);
  6174. var d = -(f + n) / (f - n);
  6175. 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);
  6176. };
  6177. /**
  6178. * Create a left-handed orthographic projection matrix
  6179. * @param left defines the viewport left coordinate
  6180. * @param right defines the viewport right coordinate
  6181. * @param bottom defines the viewport bottom coordinate
  6182. * @param top defines the viewport top coordinate
  6183. * @param znear defines the near clip plane
  6184. * @param zfar defines the far clip plane
  6185. * @returns a new matrix as a left-handed orthographic projection matrix
  6186. */
  6187. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6188. var matrix = Matrix.Zero();
  6189. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6190. return matrix;
  6191. };
  6192. /**
  6193. * Stores a left-handed orthographic projection into a given matrix
  6194. * @param left defines the viewport left coordinate
  6195. * @param right defines the viewport right coordinate
  6196. * @param bottom defines the viewport bottom coordinate
  6197. * @param top defines the viewport top coordinate
  6198. * @param znear defines the near clip plane
  6199. * @param zfar defines the far clip plane
  6200. * @param result defines the target matrix
  6201. */
  6202. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6203. var n = znear;
  6204. var f = zfar;
  6205. var a = 2.0 / (right - left);
  6206. var b = 2.0 / (top - bottom);
  6207. var c = 2.0 / (f - n);
  6208. var d = -(f + n) / (f - n);
  6209. var i0 = (left + right) / (left - right);
  6210. var i1 = (top + bottom) / (bottom - top);
  6211. 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);
  6212. };
  6213. /**
  6214. * Creates a right-handed orthographic projection matrix
  6215. * @param left defines the viewport left coordinate
  6216. * @param right defines the viewport right coordinate
  6217. * @param bottom defines the viewport bottom coordinate
  6218. * @param top defines the viewport top coordinate
  6219. * @param znear defines the near clip plane
  6220. * @param zfar defines the far clip plane
  6221. * @returns a new matrix as a right-handed orthographic projection matrix
  6222. */
  6223. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6224. var matrix = Matrix.Zero();
  6225. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6226. return matrix;
  6227. };
  6228. /**
  6229. * Stores a right-handed orthographic projection into a given matrix
  6230. * @param left defines the viewport left coordinate
  6231. * @param right defines the viewport right coordinate
  6232. * @param bottom defines the viewport bottom coordinate
  6233. * @param top defines the viewport top coordinate
  6234. * @param znear defines the near clip plane
  6235. * @param zfar defines the far clip plane
  6236. * @param result defines the target matrix
  6237. */
  6238. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6239. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6240. result.m[10] *= -1.0;
  6241. };
  6242. /**
  6243. * Creates a left-handed perspective projection matrix
  6244. * @param width defines the viewport width
  6245. * @param height defines the viewport height
  6246. * @param znear defines the near clip plane
  6247. * @param zfar defines the far clip plane
  6248. * @returns a new matrix as a left-handed perspective projection matrix
  6249. */
  6250. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6251. var matrix = Matrix.Zero();
  6252. var n = znear;
  6253. var f = zfar;
  6254. var a = 2.0 * n / width;
  6255. var b = 2.0 * n / height;
  6256. var c = (f + n) / (f - n);
  6257. var d = -2.0 * f * n / (f - n);
  6258. 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);
  6259. return matrix;
  6260. };
  6261. /**
  6262. * Creates a left-handed perspective projection matrix
  6263. * @param fov defines the horizontal field of view
  6264. * @param aspect defines the aspect ratio
  6265. * @param znear defines the near clip plane
  6266. * @param zfar defines the far clip plane
  6267. * @returns a new matrix as a left-handed perspective projection matrix
  6268. */
  6269. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6270. var matrix = Matrix.Zero();
  6271. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6272. return matrix;
  6273. };
  6274. /**
  6275. * Stores a left-handed perspective projection into a given matrix
  6276. * @param fov defines the horizontal field of view
  6277. * @param aspect defines the aspect ratio
  6278. * @param znear defines the near clip plane
  6279. * @param zfar defines the far clip plane
  6280. * @param result defines the target matrix
  6281. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6282. */
  6283. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6284. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6285. var n = znear;
  6286. var f = zfar;
  6287. var t = 1.0 / (Math.tan(fov * 0.5));
  6288. var a = isVerticalFovFixed ? (t / aspect) : t;
  6289. var b = isVerticalFovFixed ? t : (t * aspect);
  6290. var c = (f + n) / (f - n);
  6291. var d = -2.0 * f * n / (f - n);
  6292. 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);
  6293. };
  6294. /**
  6295. * Creates a right-handed perspective projection matrix
  6296. * @param fov defines the horizontal field of view
  6297. * @param aspect defines the aspect ratio
  6298. * @param znear defines the near clip plane
  6299. * @param zfar defines the far clip plane
  6300. * @returns a new matrix as a right-handed perspective projection matrix
  6301. */
  6302. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6303. var matrix = Matrix.Zero();
  6304. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6305. return matrix;
  6306. };
  6307. /**
  6308. * Stores a right-handed perspective projection into a given matrix
  6309. * @param fov defines the horizontal field of view
  6310. * @param aspect defines the aspect ratio
  6311. * @param znear defines the near clip plane
  6312. * @param zfar defines the far clip plane
  6313. * @param result defines the target matrix
  6314. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6315. */
  6316. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6317. //alternatively this could be expressed as:
  6318. // m = PerspectiveFovLHToRef
  6319. // m[10] *= -1.0;
  6320. // m[11] *= -1.0;
  6321. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6322. var n = znear;
  6323. var f = zfar;
  6324. var t = 1.0 / (Math.tan(fov * 0.5));
  6325. var a = isVerticalFovFixed ? (t / aspect) : t;
  6326. var b = isVerticalFovFixed ? t : (t * aspect);
  6327. var c = -(f + n) / (f - n);
  6328. var d = -2 * f * n / (f - n);
  6329. 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);
  6330. };
  6331. /**
  6332. * Stores a perspective projection for WebVR info a given matrix
  6333. * @param fov defines the field of view
  6334. * @param znear defines the near clip plane
  6335. * @param zfar defines the far clip plane
  6336. * @param result defines the target matrix
  6337. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6338. */
  6339. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6340. if (rightHanded === void 0) { rightHanded = false; }
  6341. var rightHandedFactor = rightHanded ? -1 : 1;
  6342. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6343. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6344. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6345. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6346. var xScale = 2.0 / (leftTan + rightTan);
  6347. var yScale = 2.0 / (upTan + downTan);
  6348. result.m[0] = xScale;
  6349. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6350. result.m[5] = yScale;
  6351. result.m[6] = result.m[7] = 0.0;
  6352. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6353. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6354. result.m[10] = -zfar / (znear - zfar);
  6355. result.m[11] = 1.0 * rightHandedFactor;
  6356. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6357. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6358. result._markAsUpdated();
  6359. };
  6360. /**
  6361. * Computes a complete transformation matrix
  6362. * @param viewport defines the viewport to use
  6363. * @param world defines the world matrix
  6364. * @param view defines the view matrix
  6365. * @param projection defines the projection matrix
  6366. * @param zmin defines the near clip plane
  6367. * @param zmax defines the far clip plane
  6368. * @returns the transformation matrix
  6369. */
  6370. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6371. var cw = viewport.width;
  6372. var ch = viewport.height;
  6373. var cx = viewport.x;
  6374. var cy = viewport.y;
  6375. 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);
  6376. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6377. };
  6378. /**
  6379. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6380. * @param matrix defines the matrix to use
  6381. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6382. */
  6383. Matrix.GetAsMatrix2x2 = function (matrix) {
  6384. return new Float32Array([
  6385. matrix.m[0], matrix.m[1],
  6386. matrix.m[4], matrix.m[5]
  6387. ]);
  6388. };
  6389. /**
  6390. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6391. * @param matrix defines the matrix to use
  6392. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6393. */
  6394. Matrix.GetAsMatrix3x3 = function (matrix) {
  6395. return new Float32Array([
  6396. matrix.m[0], matrix.m[1], matrix.m[2],
  6397. matrix.m[4], matrix.m[5], matrix.m[6],
  6398. matrix.m[8], matrix.m[9], matrix.m[10]
  6399. ]);
  6400. };
  6401. /**
  6402. * Compute the transpose of a given matrix
  6403. * @param matrix defines the matrix to transpose
  6404. * @returns the new matrix
  6405. */
  6406. Matrix.Transpose = function (matrix) {
  6407. var result = new Matrix();
  6408. Matrix.TransposeToRef(matrix, result);
  6409. return result;
  6410. };
  6411. /**
  6412. * Compute the transpose of a matrix and store it in a target matrix
  6413. * @param matrix defines the matrix to transpose
  6414. * @param result defines the target matrix
  6415. */
  6416. Matrix.TransposeToRef = function (matrix, result) {
  6417. result.m[0] = matrix.m[0];
  6418. result.m[1] = matrix.m[4];
  6419. result.m[2] = matrix.m[8];
  6420. result.m[3] = matrix.m[12];
  6421. result.m[4] = matrix.m[1];
  6422. result.m[5] = matrix.m[5];
  6423. result.m[6] = matrix.m[9];
  6424. result.m[7] = matrix.m[13];
  6425. result.m[8] = matrix.m[2];
  6426. result.m[9] = matrix.m[6];
  6427. result.m[10] = matrix.m[10];
  6428. result.m[11] = matrix.m[14];
  6429. result.m[12] = matrix.m[3];
  6430. result.m[13] = matrix.m[7];
  6431. result.m[14] = matrix.m[11];
  6432. result.m[15] = matrix.m[15];
  6433. };
  6434. /**
  6435. * Computes a reflection matrix from a plane
  6436. * @param plane defines the reflection plane
  6437. * @returns a new matrix
  6438. */
  6439. Matrix.Reflection = function (plane) {
  6440. var matrix = new Matrix();
  6441. Matrix.ReflectionToRef(plane, matrix);
  6442. return matrix;
  6443. };
  6444. /**
  6445. * Computes a reflection matrix from a plane
  6446. * @param plane defines the reflection plane
  6447. * @param result defines the target matrix
  6448. */
  6449. Matrix.ReflectionToRef = function (plane, result) {
  6450. plane.normalize();
  6451. var x = plane.normal.x;
  6452. var y = plane.normal.y;
  6453. var z = plane.normal.z;
  6454. var temp = -2 * x;
  6455. var temp2 = -2 * y;
  6456. var temp3 = -2 * z;
  6457. result.m[0] = (temp * x) + 1;
  6458. result.m[1] = temp2 * x;
  6459. result.m[2] = temp3 * x;
  6460. result.m[3] = 0.0;
  6461. result.m[4] = temp * y;
  6462. result.m[5] = (temp2 * y) + 1;
  6463. result.m[6] = temp3 * y;
  6464. result.m[7] = 0.0;
  6465. result.m[8] = temp * z;
  6466. result.m[9] = temp2 * z;
  6467. result.m[10] = (temp3 * z) + 1;
  6468. result.m[11] = 0.0;
  6469. result.m[12] = temp * plane.d;
  6470. result.m[13] = temp2 * plane.d;
  6471. result.m[14] = temp3 * plane.d;
  6472. result.m[15] = 1.0;
  6473. result._markAsUpdated();
  6474. };
  6475. /**
  6476. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6477. * @param xaxis defines the value of the 1st axis
  6478. * @param yaxis defines the value of the 2nd axis
  6479. * @param zaxis defines the value of the 3rd axis
  6480. * @param result defines the target matrix
  6481. */
  6482. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6483. result.m[0] = xaxis.x;
  6484. result.m[1] = xaxis.y;
  6485. result.m[2] = xaxis.z;
  6486. result.m[3] = 0.0;
  6487. result.m[4] = yaxis.x;
  6488. result.m[5] = yaxis.y;
  6489. result.m[6] = yaxis.z;
  6490. result.m[7] = 0.0;
  6491. result.m[8] = zaxis.x;
  6492. result.m[9] = zaxis.y;
  6493. result.m[10] = zaxis.z;
  6494. result.m[11] = 0.0;
  6495. result.m[12] = 0.0;
  6496. result.m[13] = 0.0;
  6497. result.m[14] = 0.0;
  6498. result.m[15] = 1.0;
  6499. result._markAsUpdated();
  6500. };
  6501. /**
  6502. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6503. * @param quat defines the quaternion to use
  6504. * @param result defines the target matrix
  6505. */
  6506. Matrix.FromQuaternionToRef = function (quat, result) {
  6507. var xx = quat.x * quat.x;
  6508. var yy = quat.y * quat.y;
  6509. var zz = quat.z * quat.z;
  6510. var xy = quat.x * quat.y;
  6511. var zw = quat.z * quat.w;
  6512. var zx = quat.z * quat.x;
  6513. var yw = quat.y * quat.w;
  6514. var yz = quat.y * quat.z;
  6515. var xw = quat.x * quat.w;
  6516. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6517. result.m[1] = 2.0 * (xy + zw);
  6518. result.m[2] = 2.0 * (zx - yw);
  6519. result.m[3] = 0.0;
  6520. result.m[4] = 2.0 * (xy - zw);
  6521. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6522. result.m[6] = 2.0 * (yz + xw);
  6523. result.m[7] = 0.0;
  6524. result.m[8] = 2.0 * (zx + yw);
  6525. result.m[9] = 2.0 * (yz - xw);
  6526. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6527. result.m[11] = 0.0;
  6528. result.m[12] = 0.0;
  6529. result.m[13] = 0.0;
  6530. result.m[14] = 0.0;
  6531. result.m[15] = 1.0;
  6532. result._markAsUpdated();
  6533. };
  6534. Matrix._tempQuaternion = new Quaternion();
  6535. Matrix._xAxis = Vector3.Zero();
  6536. Matrix._yAxis = Vector3.Zero();
  6537. Matrix._zAxis = Vector3.Zero();
  6538. Matrix._updateFlagSeed = 0;
  6539. Matrix._identityReadOnly = Matrix.Identity();
  6540. return Matrix;
  6541. }());
  6542. BABYLON.Matrix = Matrix;
  6543. var Plane = /** @class */ (function () {
  6544. /**
  6545. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6546. */
  6547. function Plane(a, b, c, d) {
  6548. this.normal = new Vector3(a, b, c);
  6549. this.d = d;
  6550. }
  6551. /**
  6552. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6553. */
  6554. Plane.prototype.asArray = function () {
  6555. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6556. };
  6557. // Methods
  6558. /**
  6559. * Returns a new plane copied from the current Plane.
  6560. */
  6561. Plane.prototype.clone = function () {
  6562. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6563. };
  6564. /**
  6565. * Returns the string "Plane".
  6566. */
  6567. Plane.prototype.getClassName = function () {
  6568. return "Plane";
  6569. };
  6570. /**
  6571. * Returns the Plane hash code.
  6572. */
  6573. Plane.prototype.getHashCode = function () {
  6574. var hash = this.normal.getHashCode();
  6575. hash = (hash * 397) ^ (this.d || 0);
  6576. return hash;
  6577. };
  6578. /**
  6579. * Normalize the current Plane in place.
  6580. * Returns the updated Plane.
  6581. */
  6582. Plane.prototype.normalize = function () {
  6583. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6584. var magnitude = 0.0;
  6585. if (norm !== 0) {
  6586. magnitude = 1.0 / norm;
  6587. }
  6588. this.normal.x *= magnitude;
  6589. this.normal.y *= magnitude;
  6590. this.normal.z *= magnitude;
  6591. this.d *= magnitude;
  6592. return this;
  6593. };
  6594. /**
  6595. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6596. */
  6597. Plane.prototype.transform = function (transformation) {
  6598. var transposedMatrix = Matrix.Transpose(transformation);
  6599. var x = this.normal.x;
  6600. var y = this.normal.y;
  6601. var z = this.normal.z;
  6602. var d = this.d;
  6603. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6604. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6605. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6606. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6607. return new Plane(normalX, normalY, normalZ, finalD);
  6608. };
  6609. /**
  6610. * Returns the dot product (float) of the point coordinates and the plane normal.
  6611. */
  6612. Plane.prototype.dotCoordinate = function (point) {
  6613. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6614. };
  6615. /**
  6616. * Updates the current Plane from the plane defined by the three given points.
  6617. * Returns the updated Plane.
  6618. */
  6619. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6620. var x1 = point2.x - point1.x;
  6621. var y1 = point2.y - point1.y;
  6622. var z1 = point2.z - point1.z;
  6623. var x2 = point3.x - point1.x;
  6624. var y2 = point3.y - point1.y;
  6625. var z2 = point3.z - point1.z;
  6626. var yz = (y1 * z2) - (z1 * y2);
  6627. var xz = (z1 * x2) - (x1 * z2);
  6628. var xy = (x1 * y2) - (y1 * x2);
  6629. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6630. var invPyth;
  6631. if (pyth !== 0) {
  6632. invPyth = 1.0 / pyth;
  6633. }
  6634. else {
  6635. invPyth = 0.0;
  6636. }
  6637. this.normal.x = yz * invPyth;
  6638. this.normal.y = xz * invPyth;
  6639. this.normal.z = xy * invPyth;
  6640. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6641. return this;
  6642. };
  6643. /**
  6644. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6645. */
  6646. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6647. var dot = Vector3.Dot(this.normal, direction);
  6648. return (dot <= epsilon);
  6649. };
  6650. /**
  6651. * Returns the signed distance (float) from the given point to the Plane.
  6652. */
  6653. Plane.prototype.signedDistanceTo = function (point) {
  6654. return Vector3.Dot(point, this.normal) + this.d;
  6655. };
  6656. // Statics
  6657. /**
  6658. * Returns a new Plane from the given array.
  6659. */
  6660. Plane.FromArray = function (array) {
  6661. return new Plane(array[0], array[1], array[2], array[3]);
  6662. };
  6663. /**
  6664. * Returns a new Plane defined by the three given points.
  6665. */
  6666. Plane.FromPoints = function (point1, point2, point3) {
  6667. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6668. result.copyFromPoints(point1, point2, point3);
  6669. return result;
  6670. };
  6671. /**
  6672. * Returns a new Plane the normal vector to this plane at the given origin point.
  6673. * Note : the vector "normal" is updated because normalized.
  6674. */
  6675. Plane.FromPositionAndNormal = function (origin, normal) {
  6676. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6677. normal.normalize();
  6678. result.normal = normal;
  6679. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6680. return result;
  6681. };
  6682. /**
  6683. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6684. */
  6685. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6686. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6687. return Vector3.Dot(point, normal) + d;
  6688. };
  6689. return Plane;
  6690. }());
  6691. BABYLON.Plane = Plane;
  6692. var Viewport = /** @class */ (function () {
  6693. /**
  6694. * Creates a Viewport object located at (x, y) and sized (width, height).
  6695. */
  6696. function Viewport(x, y, width, height) {
  6697. this.x = x;
  6698. this.y = y;
  6699. this.width = width;
  6700. this.height = height;
  6701. }
  6702. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6703. if (renderWidthOrEngine.getRenderWidth) {
  6704. var engine = renderWidthOrEngine;
  6705. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6706. }
  6707. var renderWidth = renderWidthOrEngine;
  6708. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6709. };
  6710. /**
  6711. * Returns a new Viewport copied from the current one.
  6712. */
  6713. Viewport.prototype.clone = function () {
  6714. return new Viewport(this.x, this.y, this.width, this.height);
  6715. };
  6716. return Viewport;
  6717. }());
  6718. BABYLON.Viewport = Viewport;
  6719. var Frustum = /** @class */ (function () {
  6720. function Frustum() {
  6721. }
  6722. /**
  6723. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6724. */
  6725. Frustum.GetPlanes = function (transform) {
  6726. var frustumPlanes = [];
  6727. for (var index = 0; index < 6; index++) {
  6728. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6729. }
  6730. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6731. return frustumPlanes;
  6732. };
  6733. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6734. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6735. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6736. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6737. frustumPlane.d = transform.m[15] + transform.m[14];
  6738. frustumPlane.normalize();
  6739. };
  6740. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6741. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6742. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6743. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6744. frustumPlane.d = transform.m[15] - transform.m[14];
  6745. frustumPlane.normalize();
  6746. };
  6747. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6748. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6749. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6750. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6751. frustumPlane.d = transform.m[15] + transform.m[12];
  6752. frustumPlane.normalize();
  6753. };
  6754. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6755. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6756. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6757. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6758. frustumPlane.d = transform.m[15] - transform.m[12];
  6759. frustumPlane.normalize();
  6760. };
  6761. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6762. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6763. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6764. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6765. frustumPlane.d = transform.m[15] - transform.m[13];
  6766. frustumPlane.normalize();
  6767. };
  6768. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6769. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6770. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6771. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6772. frustumPlane.d = transform.m[15] + transform.m[13];
  6773. frustumPlane.normalize();
  6774. };
  6775. /**
  6776. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6777. */
  6778. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6779. // Near
  6780. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6781. // Far
  6782. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6783. // Left
  6784. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6785. // Right
  6786. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6787. // Top
  6788. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6789. // Bottom
  6790. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6791. };
  6792. return Frustum;
  6793. }());
  6794. BABYLON.Frustum = Frustum;
  6795. /** Defines supported spaces */
  6796. var Space;
  6797. (function (Space) {
  6798. /** Local (object) space */
  6799. Space[Space["LOCAL"] = 0] = "LOCAL";
  6800. /** World space */
  6801. Space[Space["WORLD"] = 1] = "WORLD";
  6802. /** Bone space */
  6803. Space[Space["BONE"] = 2] = "BONE";
  6804. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6805. /** Defines the 3 main axes */
  6806. var Axis = /** @class */ (function () {
  6807. function Axis() {
  6808. }
  6809. /** X axis */
  6810. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6811. /** Y axis */
  6812. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6813. /** Z axis */
  6814. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6815. return Axis;
  6816. }());
  6817. BABYLON.Axis = Axis;
  6818. ;
  6819. var BezierCurve = /** @class */ (function () {
  6820. function BezierCurve() {
  6821. }
  6822. /**
  6823. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6824. */
  6825. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6826. // Extract X (which is equal to time here)
  6827. var f0 = 1 - 3 * x2 + 3 * x1;
  6828. var f1 = 3 * x2 - 6 * x1;
  6829. var f2 = 3 * x1;
  6830. var refinedT = t;
  6831. for (var i = 0; i < 5; i++) {
  6832. var refinedT2 = refinedT * refinedT;
  6833. var refinedT3 = refinedT2 * refinedT;
  6834. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6835. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6836. refinedT -= (x - t) * slope;
  6837. refinedT = Math.min(1, Math.max(0, refinedT));
  6838. }
  6839. // Resolve cubic bezier for the given x
  6840. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6841. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6842. Math.pow(refinedT, 3);
  6843. };
  6844. return BezierCurve;
  6845. }());
  6846. BABYLON.BezierCurve = BezierCurve;
  6847. /**
  6848. * Defines potential orientation for back face culling
  6849. */
  6850. var Orientation;
  6851. (function (Orientation) {
  6852. /**
  6853. * Clockwise
  6854. */
  6855. Orientation[Orientation["CW"] = 0] = "CW";
  6856. /** Counter clockwise */
  6857. Orientation[Orientation["CCW"] = 1] = "CCW";
  6858. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6859. /**
  6860. * Defines angle representation
  6861. */
  6862. var Angle = /** @class */ (function () {
  6863. /**
  6864. * Creates an Angle object of "radians" radians (float).
  6865. */
  6866. function Angle(radians) {
  6867. this._radians = radians;
  6868. if (this._radians < 0.0)
  6869. this._radians += (2.0 * Math.PI);
  6870. }
  6871. /**
  6872. * Get value in degrees
  6873. * @returns the Angle value in degrees (float)
  6874. */
  6875. Angle.prototype.degrees = function () {
  6876. return this._radians * 180.0 / Math.PI;
  6877. };
  6878. /**
  6879. * Get value in radians
  6880. * @returns the Angle value in radians (float)
  6881. */
  6882. Angle.prototype.radians = function () {
  6883. return this._radians;
  6884. };
  6885. /**
  6886. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6887. * @param a defines first vector
  6888. * @param b defines second vector
  6889. * @returns a new Angle
  6890. */
  6891. Angle.BetweenTwoPoints = function (a, b) {
  6892. var delta = b.subtract(a);
  6893. var theta = Math.atan2(delta.y, delta.x);
  6894. return new Angle(theta);
  6895. };
  6896. /**
  6897. * Gets a new Angle object from the given float in radians
  6898. * @param radians defines the angle value in radians
  6899. * @returns a new Angle
  6900. */
  6901. Angle.FromRadians = function (radians) {
  6902. return new Angle(radians);
  6903. };
  6904. /**
  6905. * Gets a new Angle object from the given float in degrees
  6906. * @param degrees defines the angle value in degrees
  6907. * @returns a new Angle
  6908. */
  6909. Angle.FromDegrees = function (degrees) {
  6910. return new Angle(degrees * Math.PI / 180.0);
  6911. };
  6912. return Angle;
  6913. }());
  6914. BABYLON.Angle = Angle;
  6915. var Arc2 = /** @class */ (function () {
  6916. /**
  6917. * Creates an Arc object from the three given points : start, middle and end.
  6918. */
  6919. function Arc2(startPoint, midPoint, endPoint) {
  6920. this.startPoint = startPoint;
  6921. this.midPoint = midPoint;
  6922. this.endPoint = endPoint;
  6923. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6924. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6925. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6926. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6927. 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);
  6928. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6929. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6930. var a1 = this.startAngle.degrees();
  6931. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6932. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6933. // angles correction
  6934. if (a2 - a1 > +180.0)
  6935. a2 -= 360.0;
  6936. if (a2 - a1 < -180.0)
  6937. a2 += 360.0;
  6938. if (a3 - a2 > +180.0)
  6939. a3 -= 360.0;
  6940. if (a3 - a2 < -180.0)
  6941. a3 += 360.0;
  6942. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6943. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6944. }
  6945. return Arc2;
  6946. }());
  6947. BABYLON.Arc2 = Arc2;
  6948. var Path2 = /** @class */ (function () {
  6949. /**
  6950. * Creates a Path2 object from the starting 2D coordinates x and y.
  6951. */
  6952. function Path2(x, y) {
  6953. this._points = new Array();
  6954. this._length = 0.0;
  6955. this.closed = false;
  6956. this._points.push(new Vector2(x, y));
  6957. }
  6958. /**
  6959. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6960. * Returns the updated Path2.
  6961. */
  6962. Path2.prototype.addLineTo = function (x, y) {
  6963. if (this.closed) {
  6964. return this;
  6965. }
  6966. var newPoint = new Vector2(x, y);
  6967. var previousPoint = this._points[this._points.length - 1];
  6968. this._points.push(newPoint);
  6969. this._length += newPoint.subtract(previousPoint).length();
  6970. return this;
  6971. };
  6972. /**
  6973. * 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.
  6974. * Returns the updated Path2.
  6975. */
  6976. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6977. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6978. if (this.closed) {
  6979. return this;
  6980. }
  6981. var startPoint = this._points[this._points.length - 1];
  6982. var midPoint = new Vector2(midX, midY);
  6983. var endPoint = new Vector2(endX, endY);
  6984. var arc = new Arc2(startPoint, midPoint, endPoint);
  6985. var increment = arc.angle.radians() / numberOfSegments;
  6986. if (arc.orientation === Orientation.CW)
  6987. increment *= -1;
  6988. var currentAngle = arc.startAngle.radians() + increment;
  6989. for (var i = 0; i < numberOfSegments; i++) {
  6990. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6991. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6992. this.addLineTo(x, y);
  6993. currentAngle += increment;
  6994. }
  6995. return this;
  6996. };
  6997. /**
  6998. * Closes the Path2.
  6999. * Returns the Path2.
  7000. */
  7001. Path2.prototype.close = function () {
  7002. this.closed = true;
  7003. return this;
  7004. };
  7005. /**
  7006. * Returns the Path2 total length (float).
  7007. */
  7008. Path2.prototype.length = function () {
  7009. var result = this._length;
  7010. if (!this.closed) {
  7011. var lastPoint = this._points[this._points.length - 1];
  7012. var firstPoint = this._points[0];
  7013. result += (firstPoint.subtract(lastPoint).length());
  7014. }
  7015. return result;
  7016. };
  7017. /**
  7018. * Returns the Path2 internal array of points.
  7019. */
  7020. Path2.prototype.getPoints = function () {
  7021. return this._points;
  7022. };
  7023. /**
  7024. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7025. */
  7026. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7027. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7028. return Vector2.Zero();
  7029. }
  7030. var lengthPosition = normalizedLengthPosition * this.length();
  7031. var previousOffset = 0;
  7032. for (var i = 0; i < this._points.length; i++) {
  7033. var j = (i + 1) % this._points.length;
  7034. var a = this._points[i];
  7035. var b = this._points[j];
  7036. var bToA = b.subtract(a);
  7037. var nextOffset = (bToA.length() + previousOffset);
  7038. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7039. var dir = bToA.normalize();
  7040. var localOffset = lengthPosition - previousOffset;
  7041. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7042. }
  7043. previousOffset = nextOffset;
  7044. }
  7045. return Vector2.Zero();
  7046. };
  7047. /**
  7048. * Returns a new Path2 starting at the coordinates (x, y).
  7049. */
  7050. Path2.StartingAt = function (x, y) {
  7051. return new Path2(x, y);
  7052. };
  7053. return Path2;
  7054. }());
  7055. BABYLON.Path2 = Path2;
  7056. var Path3D = /** @class */ (function () {
  7057. /**
  7058. * new Path3D(path, normal, raw)
  7059. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7060. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7061. * path : an array of Vector3, the curve axis of the Path3D
  7062. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7063. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7064. */
  7065. function Path3D(path, firstNormal, raw) {
  7066. if (firstNormal === void 0) { firstNormal = null; }
  7067. this.path = path;
  7068. this._curve = new Array();
  7069. this._distances = new Array();
  7070. this._tangents = new Array();
  7071. this._normals = new Array();
  7072. this._binormals = new Array();
  7073. for (var p = 0; p < path.length; p++) {
  7074. this._curve[p] = path[p].clone(); // hard copy
  7075. }
  7076. this._raw = raw || false;
  7077. this._compute(firstNormal);
  7078. }
  7079. /**
  7080. * Returns the Path3D array of successive Vector3 designing its curve.
  7081. */
  7082. Path3D.prototype.getCurve = function () {
  7083. return this._curve;
  7084. };
  7085. /**
  7086. * Returns an array populated with tangent vectors on each Path3D curve point.
  7087. */
  7088. Path3D.prototype.getTangents = function () {
  7089. return this._tangents;
  7090. };
  7091. /**
  7092. * Returns an array populated with normal vectors on each Path3D curve point.
  7093. */
  7094. Path3D.prototype.getNormals = function () {
  7095. return this._normals;
  7096. };
  7097. /**
  7098. * Returns an array populated with binormal vectors on each Path3D curve point.
  7099. */
  7100. Path3D.prototype.getBinormals = function () {
  7101. return this._binormals;
  7102. };
  7103. /**
  7104. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7105. */
  7106. Path3D.prototype.getDistances = function () {
  7107. return this._distances;
  7108. };
  7109. /**
  7110. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7111. * Returns the same object updated.
  7112. */
  7113. Path3D.prototype.update = function (path, firstNormal) {
  7114. if (firstNormal === void 0) { firstNormal = null; }
  7115. for (var p = 0; p < path.length; p++) {
  7116. this._curve[p].x = path[p].x;
  7117. this._curve[p].y = path[p].y;
  7118. this._curve[p].z = path[p].z;
  7119. }
  7120. this._compute(firstNormal);
  7121. return this;
  7122. };
  7123. // private function compute() : computes tangents, normals and binormals
  7124. Path3D.prototype._compute = function (firstNormal) {
  7125. var l = this._curve.length;
  7126. // first and last tangents
  7127. this._tangents[0] = this._getFirstNonNullVector(0);
  7128. if (!this._raw) {
  7129. this._tangents[0].normalize();
  7130. }
  7131. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7132. if (!this._raw) {
  7133. this._tangents[l - 1].normalize();
  7134. }
  7135. // normals and binormals at first point : arbitrary vector with _normalVector()
  7136. var tg0 = this._tangents[0];
  7137. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7138. this._normals[0] = pp0;
  7139. if (!this._raw) {
  7140. this._normals[0].normalize();
  7141. }
  7142. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7143. if (!this._raw) {
  7144. this._binormals[0].normalize();
  7145. }
  7146. this._distances[0] = 0.0;
  7147. // normals and binormals : next points
  7148. var prev; // previous vector (segment)
  7149. var cur; // current vector (segment)
  7150. var curTang; // current tangent
  7151. // previous normal
  7152. var prevBinor; // previous binormal
  7153. for (var i = 1; i < l; i++) {
  7154. // tangents
  7155. prev = this._getLastNonNullVector(i);
  7156. if (i < l - 1) {
  7157. cur = this._getFirstNonNullVector(i);
  7158. this._tangents[i] = prev.add(cur);
  7159. this._tangents[i].normalize();
  7160. }
  7161. this._distances[i] = this._distances[i - 1] + prev.length();
  7162. // normals and binormals
  7163. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7164. curTang = this._tangents[i];
  7165. prevBinor = this._binormals[i - 1];
  7166. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7167. if (!this._raw) {
  7168. this._normals[i].normalize();
  7169. }
  7170. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7171. if (!this._raw) {
  7172. this._binormals[i].normalize();
  7173. }
  7174. }
  7175. };
  7176. // private function getFirstNonNullVector(index)
  7177. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7178. Path3D.prototype._getFirstNonNullVector = function (index) {
  7179. var i = 1;
  7180. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7181. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7182. i++;
  7183. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7184. }
  7185. return nNVector;
  7186. };
  7187. // private function getLastNonNullVector(index)
  7188. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7189. Path3D.prototype._getLastNonNullVector = function (index) {
  7190. var i = 1;
  7191. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7192. while (nLVector.length() === 0 && index > i + 1) {
  7193. i++;
  7194. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7195. }
  7196. return nLVector;
  7197. };
  7198. // private function normalVector(v0, vt, va) :
  7199. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7200. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7201. Path3D.prototype._normalVector = function (v0, vt, va) {
  7202. var normal0;
  7203. var tgl = vt.length();
  7204. if (tgl === 0.0) {
  7205. tgl = 1.0;
  7206. }
  7207. if (va === undefined || va === null) {
  7208. var point;
  7209. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7210. point = new Vector3(0.0, -1.0, 0.0);
  7211. }
  7212. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7213. point = new Vector3(1.0, 0.0, 0.0);
  7214. }
  7215. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7216. point = new Vector3(0.0, 0.0, 1.0);
  7217. }
  7218. else {
  7219. point = Vector3.Zero();
  7220. }
  7221. normal0 = Vector3.Cross(vt, point);
  7222. }
  7223. else {
  7224. normal0 = Vector3.Cross(vt, va);
  7225. Vector3.CrossToRef(normal0, vt, normal0);
  7226. }
  7227. normal0.normalize();
  7228. return normal0;
  7229. };
  7230. return Path3D;
  7231. }());
  7232. BABYLON.Path3D = Path3D;
  7233. var Curve3 = /** @class */ (function () {
  7234. /**
  7235. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7236. * A Curve3 is designed from a series of successive Vector3.
  7237. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7238. */
  7239. function Curve3(points) {
  7240. this._length = 0.0;
  7241. this._points = points;
  7242. this._length = this._computeLength(points);
  7243. }
  7244. /**
  7245. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7246. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7247. * @param v1 (Vector3) the control point
  7248. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7249. * @param nbPoints (integer) the wanted number of points in the curve
  7250. */
  7251. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7252. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7253. var bez = new Array();
  7254. var equation = function (t, val0, val1, val2) {
  7255. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7256. return res;
  7257. };
  7258. for (var i = 0; i <= nbPoints; i++) {
  7259. 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)));
  7260. }
  7261. return new Curve3(bez);
  7262. };
  7263. /**
  7264. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7265. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7266. * @param v1 (Vector3) the first control point
  7267. * @param v2 (Vector3) the second control point
  7268. * @param v3 (Vector3) the end point of the Cubic Bezier
  7269. * @param nbPoints (integer) the wanted number of points in the curve
  7270. */
  7271. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7272. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7273. var bez = new Array();
  7274. var equation = function (t, val0, val1, val2, val3) {
  7275. 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;
  7276. return res;
  7277. };
  7278. for (var i = 0; i <= nbPoints; i++) {
  7279. 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)));
  7280. }
  7281. return new Curve3(bez);
  7282. };
  7283. /**
  7284. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7285. * @param p1 (Vector3) the origin point of the Hermite Spline
  7286. * @param t1 (Vector3) the tangent vector at the origin point
  7287. * @param p2 (Vector3) the end point of the Hermite Spline
  7288. * @param t2 (Vector3) the tangent vector at the end point
  7289. * @param nbPoints (integer) the wanted number of points in the curve
  7290. */
  7291. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7292. var hermite = new Array();
  7293. var step = 1.0 / nbPoints;
  7294. for (var i = 0; i <= nbPoints; i++) {
  7295. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7296. }
  7297. return new Curve3(hermite);
  7298. };
  7299. /**
  7300. * Returns a Curve3 object along a CatmullRom Spline curve :
  7301. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7302. * @param nbPoints (integer) the wanted number of points between each curve control points
  7303. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7304. */
  7305. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7306. var catmullRom = new Array();
  7307. var step = 1.0 / nbPoints;
  7308. var amount = 0.0;
  7309. if (closed) {
  7310. var pointsCount = points.length;
  7311. for (var i = 0; i < pointsCount; i++) {
  7312. amount = 0;
  7313. for (var c = 0; c < nbPoints; c++) {
  7314. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7315. amount += step;
  7316. }
  7317. }
  7318. catmullRom.push(catmullRom[0]);
  7319. }
  7320. else {
  7321. var totalPoints = new Array();
  7322. totalPoints.push(points[0].clone());
  7323. Array.prototype.push.apply(totalPoints, points);
  7324. totalPoints.push(points[points.length - 1].clone());
  7325. for (var i = 0; i < totalPoints.length - 3; i++) {
  7326. amount = 0;
  7327. for (var c = 0; c < nbPoints; c++) {
  7328. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7329. amount += step;
  7330. }
  7331. }
  7332. i--;
  7333. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7334. }
  7335. return new Curve3(catmullRom);
  7336. };
  7337. /**
  7338. * Returns the Curve3 stored array of successive Vector3
  7339. */
  7340. Curve3.prototype.getPoints = function () {
  7341. return this._points;
  7342. };
  7343. /**
  7344. * Returns the computed length (float) of the curve.
  7345. */
  7346. Curve3.prototype.length = function () {
  7347. return this._length;
  7348. };
  7349. /**
  7350. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7351. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7352. * curveA and curveB keep unchanged.
  7353. */
  7354. Curve3.prototype.continue = function (curve) {
  7355. var lastPoint = this._points[this._points.length - 1];
  7356. var continuedPoints = this._points.slice();
  7357. var curvePoints = curve.getPoints();
  7358. for (var i = 1; i < curvePoints.length; i++) {
  7359. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7360. }
  7361. var continuedCurve = new Curve3(continuedPoints);
  7362. return continuedCurve;
  7363. };
  7364. Curve3.prototype._computeLength = function (path) {
  7365. var l = 0;
  7366. for (var i = 1; i < path.length; i++) {
  7367. l += (path[i].subtract(path[i - 1])).length();
  7368. }
  7369. return l;
  7370. };
  7371. return Curve3;
  7372. }());
  7373. BABYLON.Curve3 = Curve3;
  7374. // Vertex formats
  7375. var PositionNormalVertex = /** @class */ (function () {
  7376. function PositionNormalVertex(position, normal) {
  7377. if (position === void 0) { position = Vector3.Zero(); }
  7378. if (normal === void 0) { normal = Vector3.Up(); }
  7379. this.position = position;
  7380. this.normal = normal;
  7381. }
  7382. PositionNormalVertex.prototype.clone = function () {
  7383. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7384. };
  7385. return PositionNormalVertex;
  7386. }());
  7387. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7388. var PositionNormalTextureVertex = /** @class */ (function () {
  7389. function PositionNormalTextureVertex(position, normal, uv) {
  7390. if (position === void 0) { position = Vector3.Zero(); }
  7391. if (normal === void 0) { normal = Vector3.Up(); }
  7392. if (uv === void 0) { uv = Vector2.Zero(); }
  7393. this.position = position;
  7394. this.normal = normal;
  7395. this.uv = uv;
  7396. }
  7397. PositionNormalTextureVertex.prototype.clone = function () {
  7398. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7399. };
  7400. return PositionNormalTextureVertex;
  7401. }());
  7402. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7403. // Temporary pre-allocated objects for engine internal use
  7404. // usage in any internal function :
  7405. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7406. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7407. var Tmp = /** @class */ (function () {
  7408. function Tmp() {
  7409. }
  7410. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7411. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7412. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7413. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7414. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7415. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7416. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7417. Matrix.Zero(), Matrix.Zero(),
  7418. Matrix.Zero(), Matrix.Zero(),
  7419. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7420. return Tmp;
  7421. }());
  7422. BABYLON.Tmp = Tmp;
  7423. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7424. var MathTmp = /** @class */ (function () {
  7425. function MathTmp() {
  7426. }
  7427. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7428. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7429. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7430. return MathTmp;
  7431. }());
  7432. })(BABYLON || (BABYLON = {}));
  7433. //# sourceMappingURL=babylon.math.js.map
  7434. var BABYLON;
  7435. (function (BABYLON) {
  7436. var Scalar = /** @class */ (function () {
  7437. function Scalar() {
  7438. }
  7439. /**
  7440. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7441. */
  7442. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7443. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7444. var num = a - b;
  7445. return -epsilon <= num && num <= epsilon;
  7446. };
  7447. /**
  7448. * Returns a string : the upper case translation of the number i to hexadecimal.
  7449. */
  7450. Scalar.ToHex = function (i) {
  7451. var str = i.toString(16);
  7452. if (i <= 15) {
  7453. return ("0" + str).toUpperCase();
  7454. }
  7455. return str.toUpperCase();
  7456. };
  7457. /**
  7458. * Returns -1 if value is negative and +1 is value is positive.
  7459. * Returns the value itself if it's equal to zero.
  7460. */
  7461. Scalar.Sign = function (value) {
  7462. value = +value; // convert to a number
  7463. if (value === 0 || isNaN(value))
  7464. return value;
  7465. return value > 0 ? 1 : -1;
  7466. };
  7467. /**
  7468. * Returns the value itself if it's between min and max.
  7469. * Returns min if the value is lower than min.
  7470. * Returns max if the value is greater than max.
  7471. */
  7472. Scalar.Clamp = function (value, min, max) {
  7473. if (min === void 0) { min = 0; }
  7474. if (max === void 0) { max = 1; }
  7475. return Math.min(max, Math.max(min, value));
  7476. };
  7477. /**
  7478. * Returns the log2 of value.
  7479. */
  7480. Scalar.Log2 = function (value) {
  7481. return Math.log(value) * Math.LOG2E;
  7482. };
  7483. /**
  7484. * Loops the value, so that it is never larger than length and never smaller than 0.
  7485. *
  7486. * This is similar to the modulo operator but it works with floating point numbers.
  7487. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7488. * With t = 5 and length = 2.5, the result would be 0.0.
  7489. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7490. */
  7491. Scalar.Repeat = function (value, length) {
  7492. return value - Math.floor(value / length) * length;
  7493. };
  7494. /**
  7495. * Normalize the value between 0.0 and 1.0 using min and max values
  7496. */
  7497. Scalar.Normalize = function (value, min, max) {
  7498. return (value - min) / (max - min);
  7499. };
  7500. /**
  7501. * Denormalize the value from 0.0 and 1.0 using min and max values
  7502. */
  7503. Scalar.Denormalize = function (normalized, min, max) {
  7504. return (normalized * (max - min) + min);
  7505. };
  7506. /**
  7507. * Calculates the shortest difference between two given angles given in degrees.
  7508. */
  7509. Scalar.DeltaAngle = function (current, target) {
  7510. var num = Scalar.Repeat(target - current, 360.0);
  7511. if (num > 180.0) {
  7512. num -= 360.0;
  7513. }
  7514. return num;
  7515. };
  7516. /**
  7517. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7518. *
  7519. * The returned value will move back and forth between 0 and length
  7520. */
  7521. Scalar.PingPong = function (tx, length) {
  7522. var t = Scalar.Repeat(tx, length * 2.0);
  7523. return length - Math.abs(t - length);
  7524. };
  7525. /**
  7526. * Interpolates between min and max with smoothing at the limits.
  7527. *
  7528. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7529. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7530. */
  7531. Scalar.SmoothStep = function (from, to, tx) {
  7532. var t = Scalar.Clamp(tx);
  7533. t = -2.0 * t * t * t + 3.0 * t * t;
  7534. return to * t + from * (1.0 - t);
  7535. };
  7536. /**
  7537. * Moves a value current towards target.
  7538. *
  7539. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7540. * Negative values of maxDelta pushes the value away from target.
  7541. */
  7542. Scalar.MoveTowards = function (current, target, maxDelta) {
  7543. var result = 0;
  7544. if (Math.abs(target - current) <= maxDelta) {
  7545. result = target;
  7546. }
  7547. else {
  7548. result = current + Scalar.Sign(target - current) * maxDelta;
  7549. }
  7550. return result;
  7551. };
  7552. /**
  7553. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7554. *
  7555. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7556. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7557. */
  7558. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7559. var num = Scalar.DeltaAngle(current, target);
  7560. var result = 0;
  7561. if (-maxDelta < num && num < maxDelta) {
  7562. result = target;
  7563. }
  7564. else {
  7565. target = current + num;
  7566. result = Scalar.MoveTowards(current, target, maxDelta);
  7567. }
  7568. return result;
  7569. };
  7570. /**
  7571. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7572. */
  7573. Scalar.Lerp = function (start, end, amount) {
  7574. return start + ((end - start) * amount);
  7575. };
  7576. /**
  7577. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7578. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7579. */
  7580. Scalar.LerpAngle = function (start, end, amount) {
  7581. var num = Scalar.Repeat(end - start, 360.0);
  7582. if (num > 180.0) {
  7583. num -= 360.0;
  7584. }
  7585. return start + num * Scalar.Clamp(amount);
  7586. };
  7587. /**
  7588. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7589. */
  7590. Scalar.InverseLerp = function (a, b, value) {
  7591. var result = 0;
  7592. if (a != b) {
  7593. result = Scalar.Clamp((value - a) / (b - a));
  7594. }
  7595. else {
  7596. result = 0.0;
  7597. }
  7598. return result;
  7599. };
  7600. /**
  7601. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7602. */
  7603. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7604. var squared = amount * amount;
  7605. var cubed = amount * squared;
  7606. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7607. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7608. var part3 = (cubed - (2.0 * squared)) + amount;
  7609. var part4 = cubed - squared;
  7610. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7611. };
  7612. /**
  7613. * Returns a random float number between and min and max values
  7614. */
  7615. Scalar.RandomRange = function (min, max) {
  7616. if (min === max)
  7617. return min;
  7618. return ((Math.random() * (max - min)) + min);
  7619. };
  7620. /**
  7621. * This function returns percentage of a number in a given range.
  7622. *
  7623. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7624. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7625. */
  7626. Scalar.RangeToPercent = function (number, min, max) {
  7627. return ((number - min) / (max - min));
  7628. };
  7629. /**
  7630. * This function returns number that corresponds to the percentage in a given range.
  7631. *
  7632. * PercentToRange(0.34,0,100) will return 34.
  7633. */
  7634. Scalar.PercentToRange = function (percent, min, max) {
  7635. return ((max - min) * percent + min);
  7636. };
  7637. /**
  7638. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7639. * @param angle The angle to normalize in radian.
  7640. * @return The converted angle.
  7641. */
  7642. Scalar.NormalizeRadians = function (angle) {
  7643. // More precise but slower version kept for reference.
  7644. // angle = angle % Tools.TwoPi;
  7645. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7646. //if (angle > Math.PI) {
  7647. // angle -= Tools.TwoPi;
  7648. //}
  7649. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7650. return angle;
  7651. };
  7652. /**
  7653. * Two pi constants convenient for computation.
  7654. */
  7655. Scalar.TwoPi = Math.PI * 2;
  7656. return Scalar;
  7657. }());
  7658. BABYLON.Scalar = Scalar;
  7659. })(BABYLON || (BABYLON = {}));
  7660. //# sourceMappingURL=babylon.math.scalar.js.map
  7661. //# sourceMappingURL=babylon.mixins.js.map
  7662. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7663. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7664. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7665. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7666. //# sourceMappingURL=babylon.webgl2.js.map
  7667. var BABYLON;
  7668. (function (BABYLON) {
  7669. var __decoratorInitialStore = {};
  7670. var __mergedStore = {};
  7671. var _copySource = function (creationFunction, source, instanciate) {
  7672. var destination = creationFunction();
  7673. // Tags
  7674. if (BABYLON.Tags) {
  7675. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7676. }
  7677. var classStore = getMergedStore(destination);
  7678. // Properties
  7679. for (var property in classStore) {
  7680. var propertyDescriptor = classStore[property];
  7681. var sourceProperty = source[property];
  7682. var propertyType = propertyDescriptor.type;
  7683. if (sourceProperty !== undefined && sourceProperty !== null) {
  7684. switch (propertyType) {
  7685. case 0: // Value
  7686. case 6: // Mesh reference
  7687. case 11: // Camera reference
  7688. destination[property] = sourceProperty;
  7689. break;
  7690. case 1: // Texture
  7691. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7692. break;
  7693. case 2: // Color3
  7694. case 3: // FresnelParameters
  7695. case 4: // Vector2
  7696. case 5: // Vector3
  7697. case 7: // Color Curves
  7698. case 10: // Quaternion
  7699. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7700. break;
  7701. }
  7702. }
  7703. }
  7704. return destination;
  7705. };
  7706. function getDirectStore(target) {
  7707. var classKey = target.getClassName();
  7708. if (!__decoratorInitialStore[classKey]) {
  7709. __decoratorInitialStore[classKey] = {};
  7710. }
  7711. return __decoratorInitialStore[classKey];
  7712. }
  7713. /**
  7714. * Return the list of properties flagged as serializable
  7715. * @param target: host object
  7716. */
  7717. function getMergedStore(target) {
  7718. var classKey = target.getClassName();
  7719. if (__mergedStore[classKey]) {
  7720. return __mergedStore[classKey];
  7721. }
  7722. __mergedStore[classKey] = {};
  7723. var store = __mergedStore[classKey];
  7724. var currentTarget = target;
  7725. var currentKey = classKey;
  7726. while (currentKey) {
  7727. var initialStore = __decoratorInitialStore[currentKey];
  7728. for (var property in initialStore) {
  7729. store[property] = initialStore[property];
  7730. }
  7731. var parent_1 = void 0;
  7732. var done = false;
  7733. do {
  7734. parent_1 = Object.getPrototypeOf(currentTarget);
  7735. if (!parent_1.getClassName) {
  7736. done = true;
  7737. break;
  7738. }
  7739. if (parent_1.getClassName() !== currentKey) {
  7740. break;
  7741. }
  7742. currentTarget = parent_1;
  7743. } while (parent_1);
  7744. if (done) {
  7745. break;
  7746. }
  7747. currentKey = parent_1.getClassName();
  7748. currentTarget = parent_1;
  7749. }
  7750. return store;
  7751. }
  7752. function generateSerializableMember(type, sourceName) {
  7753. return function (target, propertyKey) {
  7754. var classStore = getDirectStore(target);
  7755. if (!classStore[propertyKey]) {
  7756. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7757. }
  7758. };
  7759. }
  7760. function generateExpandMember(setCallback, targetKey) {
  7761. if (targetKey === void 0) { targetKey = null; }
  7762. return function (target, propertyKey) {
  7763. var key = targetKey || ("_" + propertyKey);
  7764. Object.defineProperty(target, propertyKey, {
  7765. get: function () {
  7766. return this[key];
  7767. },
  7768. set: function (value) {
  7769. if (this[key] === value) {
  7770. return;
  7771. }
  7772. this[key] = value;
  7773. target[setCallback].apply(this);
  7774. },
  7775. enumerable: true,
  7776. configurable: true
  7777. });
  7778. };
  7779. }
  7780. function expandToProperty(callback, targetKey) {
  7781. if (targetKey === void 0) { targetKey = null; }
  7782. return generateExpandMember(callback, targetKey);
  7783. }
  7784. BABYLON.expandToProperty = expandToProperty;
  7785. function serialize(sourceName) {
  7786. return generateSerializableMember(0, sourceName); // value member
  7787. }
  7788. BABYLON.serialize = serialize;
  7789. function serializeAsTexture(sourceName) {
  7790. return generateSerializableMember(1, sourceName); // texture member
  7791. }
  7792. BABYLON.serializeAsTexture = serializeAsTexture;
  7793. function serializeAsColor3(sourceName) {
  7794. return generateSerializableMember(2, sourceName); // color3 member
  7795. }
  7796. BABYLON.serializeAsColor3 = serializeAsColor3;
  7797. function serializeAsFresnelParameters(sourceName) {
  7798. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7799. }
  7800. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7801. function serializeAsVector2(sourceName) {
  7802. return generateSerializableMember(4, sourceName); // vector2 member
  7803. }
  7804. BABYLON.serializeAsVector2 = serializeAsVector2;
  7805. function serializeAsVector3(sourceName) {
  7806. return generateSerializableMember(5, sourceName); // vector3 member
  7807. }
  7808. BABYLON.serializeAsVector3 = serializeAsVector3;
  7809. function serializeAsMeshReference(sourceName) {
  7810. return generateSerializableMember(6, sourceName); // mesh reference member
  7811. }
  7812. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7813. function serializeAsColorCurves(sourceName) {
  7814. return generateSerializableMember(7, sourceName); // color curves
  7815. }
  7816. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7817. function serializeAsColor4(sourceName) {
  7818. return generateSerializableMember(8, sourceName); // color 4
  7819. }
  7820. BABYLON.serializeAsColor4 = serializeAsColor4;
  7821. function serializeAsImageProcessingConfiguration(sourceName) {
  7822. return generateSerializableMember(9, sourceName); // image processing
  7823. }
  7824. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7825. function serializeAsQuaternion(sourceName) {
  7826. return generateSerializableMember(10, sourceName); // quaternion member
  7827. }
  7828. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7829. /**
  7830. * Decorator used to define property that can be serialized as reference to a camera
  7831. * @param sourceName defines the name of the property to decorate
  7832. */
  7833. function serializeAsCameraReference(sourceName) {
  7834. return generateSerializableMember(11, sourceName); // camera reference member
  7835. }
  7836. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7837. var SerializationHelper = /** @class */ (function () {
  7838. function SerializationHelper() {
  7839. }
  7840. SerializationHelper.Serialize = function (entity, serializationObject) {
  7841. if (!serializationObject) {
  7842. serializationObject = {};
  7843. }
  7844. // Tags
  7845. if (BABYLON.Tags) {
  7846. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7847. }
  7848. var serializedProperties = getMergedStore(entity);
  7849. // Properties
  7850. for (var property in serializedProperties) {
  7851. var propertyDescriptor = serializedProperties[property];
  7852. var targetPropertyName = propertyDescriptor.sourceName || property;
  7853. var propertyType = propertyDescriptor.type;
  7854. var sourceProperty = entity[property];
  7855. if (sourceProperty !== undefined && sourceProperty !== null) {
  7856. switch (propertyType) {
  7857. case 0: // Value
  7858. serializationObject[targetPropertyName] = sourceProperty;
  7859. break;
  7860. case 1: // Texture
  7861. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7862. break;
  7863. case 2: // Color3
  7864. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7865. break;
  7866. case 3: // FresnelParameters
  7867. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7868. break;
  7869. case 4: // Vector2
  7870. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7871. break;
  7872. case 5: // Vector3
  7873. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7874. break;
  7875. case 6: // Mesh reference
  7876. serializationObject[targetPropertyName] = sourceProperty.id;
  7877. break;
  7878. case 7: // Color Curves
  7879. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7880. break;
  7881. case 8: // Color 4
  7882. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7883. break;
  7884. case 9: // Image Processing
  7885. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7886. break;
  7887. case 10: // Quaternion
  7888. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7889. break;
  7890. case 11: // Camera reference
  7891. serializationObject[targetPropertyName] = sourceProperty.id;
  7892. break;
  7893. }
  7894. }
  7895. }
  7896. return serializationObject;
  7897. };
  7898. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7899. if (rootUrl === void 0) { rootUrl = null; }
  7900. var destination = creationFunction();
  7901. if (!rootUrl) {
  7902. rootUrl = "";
  7903. }
  7904. // Tags
  7905. if (BABYLON.Tags) {
  7906. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7907. }
  7908. var classStore = getMergedStore(destination);
  7909. // Properties
  7910. for (var property in classStore) {
  7911. var propertyDescriptor = classStore[property];
  7912. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7913. var propertyType = propertyDescriptor.type;
  7914. if (sourceProperty !== undefined && sourceProperty !== null) {
  7915. var dest = destination;
  7916. switch (propertyType) {
  7917. case 0: // Value
  7918. dest[property] = sourceProperty;
  7919. break;
  7920. case 1: // Texture
  7921. if (scene) {
  7922. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7923. }
  7924. break;
  7925. case 2: // Color3
  7926. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7927. break;
  7928. case 3: // FresnelParameters
  7929. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7930. break;
  7931. case 4: // Vector2
  7932. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7933. break;
  7934. case 5: // Vector3
  7935. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7936. break;
  7937. case 6: // Mesh reference
  7938. if (scene) {
  7939. dest[property] = scene.getLastMeshByID(sourceProperty);
  7940. }
  7941. break;
  7942. case 7: // Color Curves
  7943. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7944. break;
  7945. case 8: // Color 4
  7946. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7947. break;
  7948. case 9: // Image Processing
  7949. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7950. break;
  7951. case 10: // Quaternion
  7952. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7953. break;
  7954. case 11: // Camera reference
  7955. if (scene) {
  7956. dest[property] = scene.getCameraByID(sourceProperty);
  7957. }
  7958. break;
  7959. }
  7960. }
  7961. }
  7962. return destination;
  7963. };
  7964. SerializationHelper.Clone = function (creationFunction, source) {
  7965. return _copySource(creationFunction, source, false);
  7966. };
  7967. SerializationHelper.Instanciate = function (creationFunction, source) {
  7968. return _copySource(creationFunction, source, true);
  7969. };
  7970. return SerializationHelper;
  7971. }());
  7972. BABYLON.SerializationHelper = SerializationHelper;
  7973. })(BABYLON || (BABYLON = {}));
  7974. //# sourceMappingURL=babylon.decorators.js.map
  7975. var BABYLON;
  7976. (function (BABYLON) {
  7977. /**
  7978. * Wrapper class for promise with external resolve and reject.
  7979. */
  7980. var Deferred = /** @class */ (function () {
  7981. /**
  7982. * Constructor for this deferred object.
  7983. */
  7984. function Deferred() {
  7985. var _this = this;
  7986. this.promise = new Promise(function (resolve, reject) {
  7987. _this._resolve = resolve;
  7988. _this._reject = reject;
  7989. });
  7990. }
  7991. Object.defineProperty(Deferred.prototype, "resolve", {
  7992. /**
  7993. * The resolve method of the promise associated with this deferred object.
  7994. */
  7995. get: function () {
  7996. return this._resolve;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. Object.defineProperty(Deferred.prototype, "reject", {
  8002. /**
  8003. * The reject method of the promise associated with this deferred object.
  8004. */
  8005. get: function () {
  8006. return this._reject;
  8007. },
  8008. enumerable: true,
  8009. configurable: true
  8010. });
  8011. return Deferred;
  8012. }());
  8013. BABYLON.Deferred = Deferred;
  8014. })(BABYLON || (BABYLON = {}));
  8015. //# sourceMappingURL=babylon.deferred.js.map
  8016. var BABYLON;
  8017. (function (BABYLON) {
  8018. /**
  8019. * A class serves as a medium between the observable and its observers
  8020. */
  8021. var EventState = /** @class */ (function () {
  8022. /**
  8023. * Create a new EventState
  8024. * @param mask defines the mask associated with this state
  8025. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8026. * @param target defines the original target of the state
  8027. * @param currentTarget defines the current target of the state
  8028. */
  8029. function EventState(mask, skipNextObservers, target, currentTarget) {
  8030. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8031. this.initalize(mask, skipNextObservers, target, currentTarget);
  8032. }
  8033. /**
  8034. * Initialize the current event state
  8035. * @param mask defines the mask associated with this state
  8036. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8037. * @param target defines the original target of the state
  8038. * @param currentTarget defines the current target of the state
  8039. * @returns the current event state
  8040. */
  8041. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8042. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8043. this.mask = mask;
  8044. this.skipNextObservers = skipNextObservers;
  8045. this.target = target;
  8046. this.currentTarget = currentTarget;
  8047. return this;
  8048. };
  8049. return EventState;
  8050. }());
  8051. BABYLON.EventState = EventState;
  8052. /**
  8053. * Represent an Observer registered to a given Observable object.
  8054. */
  8055. var Observer = /** @class */ (function () {
  8056. /**
  8057. * Creates a new observer
  8058. * @param callback defines the callback to call when the observer is notified
  8059. * @param mask defines the mask of the observer (used to filter notifications)
  8060. * @param scope defines the current scope used to restore the JS context
  8061. */
  8062. function Observer(
  8063. /**
  8064. * Defines the callback to call when the observer is notified
  8065. */
  8066. callback,
  8067. /**
  8068. * Defines the mask of the observer (used to filter notifications)
  8069. */
  8070. mask,
  8071. /**
  8072. * Defines the current scope used to restore the JS context
  8073. */
  8074. scope) {
  8075. if (scope === void 0) { scope = null; }
  8076. this.callback = callback;
  8077. this.mask = mask;
  8078. this.scope = scope;
  8079. /** @hidden */
  8080. this._willBeUnregistered = false;
  8081. /**
  8082. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8083. */
  8084. this.unregisterOnNextCall = false;
  8085. }
  8086. return Observer;
  8087. }());
  8088. BABYLON.Observer = Observer;
  8089. /**
  8090. * Represent a list of observers registered to multiple Observables object.
  8091. */
  8092. var MultiObserver = /** @class */ (function () {
  8093. function MultiObserver() {
  8094. }
  8095. /**
  8096. * Release associated resources
  8097. */
  8098. MultiObserver.prototype.dispose = function () {
  8099. if (this._observers && this._observables) {
  8100. for (var index = 0; index < this._observers.length; index++) {
  8101. this._observables[index].remove(this._observers[index]);
  8102. }
  8103. }
  8104. this._observers = null;
  8105. this._observables = null;
  8106. };
  8107. /**
  8108. * Raise a callback when one of the observable will notify
  8109. * @param observables defines a list of observables to watch
  8110. * @param callback defines the callback to call on notification
  8111. * @param mask defines the mask used to filter notifications
  8112. * @param scope defines the current scope used to restore the JS context
  8113. * @returns the new MultiObserver
  8114. */
  8115. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8116. if (mask === void 0) { mask = -1; }
  8117. if (scope === void 0) { scope = null; }
  8118. var result = new MultiObserver();
  8119. result._observers = new Array();
  8120. result._observables = observables;
  8121. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8122. var observable = observables_1[_i];
  8123. var observer = observable.add(callback, mask, false, scope);
  8124. if (observer) {
  8125. result._observers.push(observer);
  8126. }
  8127. }
  8128. return result;
  8129. };
  8130. return MultiObserver;
  8131. }());
  8132. BABYLON.MultiObserver = MultiObserver;
  8133. /**
  8134. * The Observable class is a simple implementation of the Observable pattern.
  8135. *
  8136. * 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.
  8137. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8138. * 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).
  8139. * 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.
  8140. */
  8141. var Observable = /** @class */ (function () {
  8142. /**
  8143. * Creates a new observable
  8144. * @param onObserverAdded defines a callback to call when a new observer is added
  8145. */
  8146. function Observable(onObserverAdded) {
  8147. this._observers = new Array();
  8148. this._eventState = new EventState(0);
  8149. if (onObserverAdded) {
  8150. this._onObserverAdded = onObserverAdded;
  8151. }
  8152. }
  8153. /**
  8154. * Create a new Observer with the specified callback
  8155. * @param callback the callback that will be executed for that Observer
  8156. * @param mask the mask used to filter observers
  8157. * @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.
  8158. * @param scope optional scope for the callback to be called from
  8159. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8160. * @returns the new observer created for the callback
  8161. */
  8162. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8163. if (mask === void 0) { mask = -1; }
  8164. if (insertFirst === void 0) { insertFirst = false; }
  8165. if (scope === void 0) { scope = null; }
  8166. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8167. if (!callback) {
  8168. return null;
  8169. }
  8170. var observer = new Observer(callback, mask, scope);
  8171. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8172. if (insertFirst) {
  8173. this._observers.unshift(observer);
  8174. }
  8175. else {
  8176. this._observers.push(observer);
  8177. }
  8178. if (this._onObserverAdded) {
  8179. this._onObserverAdded(observer);
  8180. }
  8181. return observer;
  8182. };
  8183. /**
  8184. * Create a new Observer with the specified callback and unregisters after the next notification
  8185. * @param callback the callback that will be executed for that Observer
  8186. * @returns the new observer created for the callback
  8187. */
  8188. Observable.prototype.addOnce = function (callback) {
  8189. return this.add(callback, undefined, undefined, undefined, true);
  8190. };
  8191. /**
  8192. * Remove an Observer from the Observable object
  8193. * @param observer the instance of the Observer to remove
  8194. * @returns false if it doesn't belong to this Observable
  8195. */
  8196. Observable.prototype.remove = function (observer) {
  8197. if (!observer) {
  8198. return false;
  8199. }
  8200. var index = this._observers.indexOf(observer);
  8201. if (index !== -1) {
  8202. this._observers.splice(index, 1);
  8203. return true;
  8204. }
  8205. return false;
  8206. };
  8207. /**
  8208. * Remove a callback from the Observable object
  8209. * @param callback the callback to remove
  8210. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8211. * @returns false if it doesn't belong to this Observable
  8212. */
  8213. Observable.prototype.removeCallback = function (callback, scope) {
  8214. for (var index = 0; index < this._observers.length; index++) {
  8215. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8216. this._observers.splice(index, 1);
  8217. return true;
  8218. }
  8219. }
  8220. return false;
  8221. };
  8222. Observable.prototype._deferUnregister = function (observer) {
  8223. var _this = this;
  8224. observer.unregisterOnNextCall = false;
  8225. observer._willBeUnregistered = true;
  8226. BABYLON.Tools.SetImmediate(function () {
  8227. _this.remove(observer);
  8228. });
  8229. };
  8230. /**
  8231. * Notify all Observers by calling their respective callback with the given data
  8232. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8233. * @param eventData defines the data to send to all observers
  8234. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8235. * @param target defines the original target of the state
  8236. * @param currentTarget defines the current target of the state
  8237. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8238. */
  8239. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8240. if (mask === void 0) { mask = -1; }
  8241. if (!this._observers.length) {
  8242. return true;
  8243. }
  8244. var state = this._eventState;
  8245. state.mask = mask;
  8246. state.target = target;
  8247. state.currentTarget = currentTarget;
  8248. state.skipNextObservers = false;
  8249. state.lastReturnValue = eventData;
  8250. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8251. var obs = _a[_i];
  8252. if (obs._willBeUnregistered) {
  8253. continue;
  8254. }
  8255. if (obs.mask & mask) {
  8256. if (obs.scope) {
  8257. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8258. }
  8259. else {
  8260. state.lastReturnValue = obs.callback(eventData, state);
  8261. }
  8262. if (obs.unregisterOnNextCall) {
  8263. this._deferUnregister(obs);
  8264. }
  8265. }
  8266. if (state.skipNextObservers) {
  8267. return false;
  8268. }
  8269. }
  8270. return true;
  8271. };
  8272. /**
  8273. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8274. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8275. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8276. * and it is crucial that all callbacks will be executed.
  8277. * The order of the callbacks is kept, callbacks are not executed parallel.
  8278. *
  8279. * @param eventData The data to be sent to each callback
  8280. * @param mask is used to filter observers defaults to -1
  8281. * @param target defines the callback target (see EventState)
  8282. * @param currentTarget defines he current object in the bubbling phase
  8283. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8284. */
  8285. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8286. var _this = this;
  8287. if (mask === void 0) { mask = -1; }
  8288. // create an empty promise
  8289. var p = Promise.resolve(eventData);
  8290. // no observers? return this promise.
  8291. if (!this._observers.length) {
  8292. return p;
  8293. }
  8294. var state = this._eventState;
  8295. state.mask = mask;
  8296. state.target = target;
  8297. state.currentTarget = currentTarget;
  8298. state.skipNextObservers = false;
  8299. // execute one callback after another (not using Promise.all, the order is important)
  8300. this._observers.forEach(function (obs) {
  8301. if (state.skipNextObservers) {
  8302. return;
  8303. }
  8304. if (obs._willBeUnregistered) {
  8305. return;
  8306. }
  8307. if (obs.mask & mask) {
  8308. if (obs.scope) {
  8309. p = p.then(function (lastReturnedValue) {
  8310. state.lastReturnValue = lastReturnedValue;
  8311. return obs.callback.apply(obs.scope, [eventData, state]);
  8312. });
  8313. }
  8314. else {
  8315. p = p.then(function (lastReturnedValue) {
  8316. state.lastReturnValue = lastReturnedValue;
  8317. return obs.callback(eventData, state);
  8318. });
  8319. }
  8320. if (obs.unregisterOnNextCall) {
  8321. _this._deferUnregister(obs);
  8322. }
  8323. }
  8324. });
  8325. // return the eventData
  8326. return p.then(function () { return eventData; });
  8327. };
  8328. /**
  8329. * Notify a specific observer
  8330. * @param observer defines the observer to notify
  8331. * @param eventData defines the data to be sent to each callback
  8332. * @param mask is used to filter observers defaults to -1
  8333. */
  8334. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8335. if (mask === void 0) { mask = -1; }
  8336. var state = this._eventState;
  8337. state.mask = mask;
  8338. state.skipNextObservers = false;
  8339. observer.callback(eventData, state);
  8340. };
  8341. /**
  8342. * Gets a boolean indicating if the observable has at least one observer
  8343. * @returns true is the Observable has at least one Observer registered
  8344. */
  8345. Observable.prototype.hasObservers = function () {
  8346. return this._observers.length > 0;
  8347. };
  8348. /**
  8349. * Clear the list of observers
  8350. */
  8351. Observable.prototype.clear = function () {
  8352. this._observers = new Array();
  8353. this._onObserverAdded = null;
  8354. };
  8355. /**
  8356. * Clone the current observable
  8357. * @returns a new observable
  8358. */
  8359. Observable.prototype.clone = function () {
  8360. var result = new Observable();
  8361. result._observers = this._observers.slice(0);
  8362. return result;
  8363. };
  8364. /**
  8365. * Does this observable handles observer registered with a given mask
  8366. * @param mask defines the mask to be tested
  8367. * @return whether or not one observer registered with the given mask is handeled
  8368. **/
  8369. Observable.prototype.hasSpecificMask = function (mask) {
  8370. if (mask === void 0) { mask = -1; }
  8371. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8372. var obs = _a[_i];
  8373. if (obs.mask & mask || obs.mask === mask) {
  8374. return true;
  8375. }
  8376. }
  8377. return false;
  8378. };
  8379. return Observable;
  8380. }());
  8381. BABYLON.Observable = Observable;
  8382. })(BABYLON || (BABYLON = {}));
  8383. //# sourceMappingURL=babylon.observable.js.map
  8384. var BABYLON;
  8385. (function (BABYLON) {
  8386. var SmartArray = /** @class */ (function () {
  8387. function SmartArray(capacity) {
  8388. this.length = 0;
  8389. this.data = new Array(capacity);
  8390. this._id = SmartArray._GlobalId++;
  8391. }
  8392. SmartArray.prototype.push = function (value) {
  8393. this.data[this.length++] = value;
  8394. if (this.length > this.data.length) {
  8395. this.data.length *= 2;
  8396. }
  8397. };
  8398. SmartArray.prototype.forEach = function (func) {
  8399. for (var index = 0; index < this.length; index++) {
  8400. func(this.data[index]);
  8401. }
  8402. };
  8403. SmartArray.prototype.sort = function (compareFn) {
  8404. this.data.sort(compareFn);
  8405. };
  8406. SmartArray.prototype.reset = function () {
  8407. this.length = 0;
  8408. };
  8409. SmartArray.prototype.dispose = function () {
  8410. this.reset();
  8411. if (this.data) {
  8412. this.data.length = 0;
  8413. this.data = [];
  8414. }
  8415. };
  8416. SmartArray.prototype.concat = function (array) {
  8417. if (array.length === 0) {
  8418. return;
  8419. }
  8420. if (this.length + array.length > this.data.length) {
  8421. this.data.length = (this.length + array.length) * 2;
  8422. }
  8423. for (var index = 0; index < array.length; index++) {
  8424. this.data[this.length++] = (array.data || array)[index];
  8425. }
  8426. };
  8427. SmartArray.prototype.indexOf = function (value) {
  8428. var position = this.data.indexOf(value);
  8429. if (position >= this.length) {
  8430. return -1;
  8431. }
  8432. return position;
  8433. };
  8434. SmartArray.prototype.contains = function (value) {
  8435. return this.data.indexOf(value) !== -1;
  8436. };
  8437. // Statics
  8438. SmartArray._GlobalId = 0;
  8439. return SmartArray;
  8440. }());
  8441. BABYLON.SmartArray = SmartArray;
  8442. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8443. __extends(SmartArrayNoDuplicate, _super);
  8444. function SmartArrayNoDuplicate() {
  8445. var _this = _super !== null && _super.apply(this, arguments) || this;
  8446. _this._duplicateId = 0;
  8447. return _this;
  8448. }
  8449. SmartArrayNoDuplicate.prototype.push = function (value) {
  8450. _super.prototype.push.call(this, value);
  8451. if (!value.__smartArrayFlags) {
  8452. value.__smartArrayFlags = {};
  8453. }
  8454. value.__smartArrayFlags[this._id] = this._duplicateId;
  8455. };
  8456. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8457. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8458. return false;
  8459. }
  8460. this.push(value);
  8461. return true;
  8462. };
  8463. SmartArrayNoDuplicate.prototype.reset = function () {
  8464. _super.prototype.reset.call(this);
  8465. this._duplicateId++;
  8466. };
  8467. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8468. if (array.length === 0) {
  8469. return;
  8470. }
  8471. if (this.length + array.length > this.data.length) {
  8472. this.data.length = (this.length + array.length) * 2;
  8473. }
  8474. for (var index = 0; index < array.length; index++) {
  8475. var item = (array.data || array)[index];
  8476. this.pushNoDuplicate(item);
  8477. }
  8478. };
  8479. return SmartArrayNoDuplicate;
  8480. }(SmartArray));
  8481. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8482. })(BABYLON || (BABYLON = {}));
  8483. //# sourceMappingURL=babylon.smartArray.js.map
  8484. var BABYLON;
  8485. (function (BABYLON) {
  8486. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8487. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8488. var LoadFileError = /** @class */ (function (_super) {
  8489. __extends(LoadFileError, _super);
  8490. function LoadFileError(message, request) {
  8491. var _this = _super.call(this, message) || this;
  8492. _this.request = request;
  8493. _this.name = "LoadFileError";
  8494. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8495. return _this;
  8496. }
  8497. // Polyfill for Object.setPrototypeOf if necessary.
  8498. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8499. return LoadFileError;
  8500. }(Error));
  8501. BABYLON.LoadFileError = LoadFileError;
  8502. var RetryStrategy = /** @class */ (function () {
  8503. function RetryStrategy() {
  8504. }
  8505. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8506. if (maxRetries === void 0) { maxRetries = 3; }
  8507. if (baseInterval === void 0) { baseInterval = 500; }
  8508. return function (url, request, retryIndex) {
  8509. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8510. return -1;
  8511. }
  8512. return Math.pow(2, retryIndex) * baseInterval;
  8513. };
  8514. };
  8515. return RetryStrategy;
  8516. }());
  8517. BABYLON.RetryStrategy = RetryStrategy;
  8518. // Screenshots
  8519. var screenshotCanvas;
  8520. var cloneValue = function (source, destinationObject) {
  8521. if (!source)
  8522. return null;
  8523. if (source instanceof BABYLON.Mesh) {
  8524. return null;
  8525. }
  8526. if (source instanceof BABYLON.SubMesh) {
  8527. return source.clone(destinationObject);
  8528. }
  8529. else if (source.clone) {
  8530. return source.clone();
  8531. }
  8532. return null;
  8533. };
  8534. var Tools = /** @class */ (function () {
  8535. function Tools() {
  8536. }
  8537. /**
  8538. * Interpolates between a and b via alpha
  8539. * @param a The lower value (returned when alpha = 0)
  8540. * @param b The upper value (returned when alpha = 1)
  8541. * @param alpha The interpolation-factor
  8542. * @return The mixed value
  8543. */
  8544. Tools.Mix = function (a, b, alpha) {
  8545. return a * (1 - alpha) + b * alpha;
  8546. };
  8547. Tools.Instantiate = function (className) {
  8548. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8549. return Tools.RegisteredExternalClasses[className];
  8550. }
  8551. var arr = className.split(".");
  8552. var fn = (window || this);
  8553. for (var i = 0, len = arr.length; i < len; i++) {
  8554. fn = fn[arr[i]];
  8555. }
  8556. if (typeof fn !== "function") {
  8557. return null;
  8558. }
  8559. return fn;
  8560. };
  8561. /**
  8562. * Provides a slice function that will work even on IE
  8563. * @param data defines the array to slice
  8564. * @param start defines the start of the data (optional)
  8565. * @param end defines the end of the data (optional)
  8566. * @returns the new sliced array
  8567. */
  8568. Tools.Slice = function (data, start, end) {
  8569. if (data.slice) {
  8570. return data.slice(start, end);
  8571. }
  8572. return Array.prototype.slice.call(data, start, end);
  8573. };
  8574. Tools.SetImmediate = function (action) {
  8575. if (window.setImmediate) {
  8576. window.setImmediate(action);
  8577. }
  8578. else {
  8579. setTimeout(action, 1);
  8580. }
  8581. };
  8582. Tools.IsExponentOfTwo = function (value) {
  8583. var count = 1;
  8584. do {
  8585. count *= 2;
  8586. } while (count < value);
  8587. return count === value;
  8588. };
  8589. /**
  8590. * Returns the nearest 32-bit single precision float representation of a Number
  8591. * @param value A Number. If the parameter is of a different type, it will get converted
  8592. * to a number or to NaN if it cannot be converted
  8593. * @returns number
  8594. */
  8595. Tools.FloatRound = function (value) {
  8596. if (Math.fround) {
  8597. return Math.fround(value);
  8598. }
  8599. return (Tools._tmpFloatArray[0] = value);
  8600. };
  8601. /**
  8602. * Find the next highest power of two.
  8603. * @param x Number to start search from.
  8604. * @return Next highest power of two.
  8605. */
  8606. Tools.CeilingPOT = function (x) {
  8607. x--;
  8608. x |= x >> 1;
  8609. x |= x >> 2;
  8610. x |= x >> 4;
  8611. x |= x >> 8;
  8612. x |= x >> 16;
  8613. x++;
  8614. return x;
  8615. };
  8616. /**
  8617. * Find the next lowest power of two.
  8618. * @param x Number to start search from.
  8619. * @return Next lowest power of two.
  8620. */
  8621. Tools.FloorPOT = function (x) {
  8622. x = x | (x >> 1);
  8623. x = x | (x >> 2);
  8624. x = x | (x >> 4);
  8625. x = x | (x >> 8);
  8626. x = x | (x >> 16);
  8627. return x - (x >> 1);
  8628. };
  8629. /**
  8630. * Find the nearest power of two.
  8631. * @param x Number to start search from.
  8632. * @return Next nearest power of two.
  8633. */
  8634. Tools.NearestPOT = function (x) {
  8635. var c = Tools.CeilingPOT(x);
  8636. var f = Tools.FloorPOT(x);
  8637. return (c - x) > (x - f) ? f : c;
  8638. };
  8639. Tools.GetExponentOfTwo = function (value, max, mode) {
  8640. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8641. var pot;
  8642. switch (mode) {
  8643. case BABYLON.Engine.SCALEMODE_FLOOR:
  8644. pot = Tools.FloorPOT(value);
  8645. break;
  8646. case BABYLON.Engine.SCALEMODE_NEAREST:
  8647. pot = Tools.NearestPOT(value);
  8648. break;
  8649. case BABYLON.Engine.SCALEMODE_CEILING:
  8650. default:
  8651. pot = Tools.CeilingPOT(value);
  8652. break;
  8653. }
  8654. return Math.min(pot, max);
  8655. };
  8656. Tools.GetFilename = function (path) {
  8657. var index = path.lastIndexOf("/");
  8658. if (index < 0)
  8659. return path;
  8660. return path.substring(index + 1);
  8661. };
  8662. /**
  8663. * Extracts the "folder" part of a path (everything before the filename).
  8664. * @param uri The URI to extract the info from
  8665. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8666. * @returns The "folder" part of the path
  8667. */
  8668. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8669. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8670. var index = uri.lastIndexOf("/");
  8671. if (index < 0) {
  8672. if (returnUnchangedIfNoSlash) {
  8673. return uri;
  8674. }
  8675. return "";
  8676. }
  8677. return uri.substring(0, index + 1);
  8678. };
  8679. Tools.GetDOMTextContent = function (element) {
  8680. var result = "";
  8681. var child = element.firstChild;
  8682. while (child) {
  8683. if (child.nodeType === 3) {
  8684. result += child.textContent;
  8685. }
  8686. child = child.nextSibling;
  8687. }
  8688. return result;
  8689. };
  8690. Tools.ToDegrees = function (angle) {
  8691. return angle * 180 / Math.PI;
  8692. };
  8693. Tools.ToRadians = function (angle) {
  8694. return angle * Math.PI / 180;
  8695. };
  8696. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8697. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8698. var output = "";
  8699. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8700. var i = 0;
  8701. var bytes = new Uint8Array(buffer);
  8702. while (i < bytes.length) {
  8703. chr1 = bytes[i++];
  8704. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8705. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8706. enc1 = chr1 >> 2;
  8707. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8708. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8709. enc4 = chr3 & 63;
  8710. if (isNaN(chr2)) {
  8711. enc3 = enc4 = 64;
  8712. }
  8713. else if (isNaN(chr3)) {
  8714. enc4 = 64;
  8715. }
  8716. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8717. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8718. }
  8719. return "data:image/png;base64," + output;
  8720. };
  8721. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8722. if (bias === void 0) { bias = null; }
  8723. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8724. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8725. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8726. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8727. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8728. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8729. }
  8730. if (bias) {
  8731. minimum.x -= minimum.x * bias.x + bias.y;
  8732. minimum.y -= minimum.y * bias.x + bias.y;
  8733. minimum.z -= minimum.z * bias.x + bias.y;
  8734. maximum.x += maximum.x * bias.x + bias.y;
  8735. maximum.y += maximum.y * bias.x + bias.y;
  8736. maximum.z += maximum.z * bias.x + bias.y;
  8737. }
  8738. return {
  8739. minimum: minimum,
  8740. maximum: maximum
  8741. };
  8742. };
  8743. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8744. if (bias === void 0) { bias = null; }
  8745. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8746. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8747. if (!stride) {
  8748. stride = 3;
  8749. }
  8750. for (var index = start; index < start + count; index++) {
  8751. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8752. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8753. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8754. }
  8755. if (bias) {
  8756. minimum.x -= minimum.x * bias.x + bias.y;
  8757. minimum.y -= minimum.y * bias.x + bias.y;
  8758. minimum.z -= minimum.z * bias.x + bias.y;
  8759. maximum.x += maximum.x * bias.x + bias.y;
  8760. maximum.y += maximum.y * bias.x + bias.y;
  8761. maximum.z += maximum.z * bias.x + bias.y;
  8762. }
  8763. return {
  8764. minimum: minimum,
  8765. maximum: maximum
  8766. };
  8767. };
  8768. Tools.Vector2ArrayFeeder = function (array) {
  8769. return function (index) {
  8770. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8771. var length = isFloatArray ? array.length / 2 : array.length;
  8772. if (index >= length) {
  8773. return null;
  8774. }
  8775. if (isFloatArray) {
  8776. var fa = array;
  8777. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8778. }
  8779. var a = array;
  8780. return a[index];
  8781. };
  8782. };
  8783. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8784. if (bias === void 0) { bias = null; }
  8785. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8786. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8787. var i = 0;
  8788. var cur = feeder(i++);
  8789. while (cur) {
  8790. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8791. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8792. cur = feeder(i++);
  8793. }
  8794. if (bias) {
  8795. minimum.x -= minimum.x * bias.x + bias.y;
  8796. minimum.y -= minimum.y * bias.x + bias.y;
  8797. maximum.x += maximum.x * bias.x + bias.y;
  8798. maximum.y += maximum.y * bias.x + bias.y;
  8799. }
  8800. return {
  8801. minimum: minimum,
  8802. maximum: maximum
  8803. };
  8804. };
  8805. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8806. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8807. return null;
  8808. return Array.isArray(obj) ? obj : [obj];
  8809. };
  8810. // Misc.
  8811. Tools.GetPointerPrefix = function () {
  8812. var eventPrefix = "pointer";
  8813. // Check if pointer events are supported
  8814. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8815. eventPrefix = "mouse";
  8816. }
  8817. return eventPrefix;
  8818. };
  8819. /**
  8820. * @param func - the function to be called
  8821. * @param requester - the object that will request the next frame. Falls back to window.
  8822. */
  8823. Tools.QueueNewFrame = function (func, requester) {
  8824. if (!Tools.IsWindowObjectExist()) {
  8825. return setTimeout(func, 16);
  8826. }
  8827. if (!requester) {
  8828. requester = window;
  8829. }
  8830. if (requester.requestAnimationFrame) {
  8831. return requester.requestAnimationFrame(func);
  8832. }
  8833. else if (requester.msRequestAnimationFrame) {
  8834. return requester.msRequestAnimationFrame(func);
  8835. }
  8836. else if (requester.webkitRequestAnimationFrame) {
  8837. return requester.webkitRequestAnimationFrame(func);
  8838. }
  8839. else if (requester.mozRequestAnimationFrame) {
  8840. return requester.mozRequestAnimationFrame(func);
  8841. }
  8842. else if (requester.oRequestAnimationFrame) {
  8843. return requester.oRequestAnimationFrame(func);
  8844. }
  8845. else {
  8846. return window.setTimeout(func, 16);
  8847. }
  8848. };
  8849. Tools.RequestFullscreen = function (element) {
  8850. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8851. if (!requestFunction)
  8852. return;
  8853. requestFunction.call(element);
  8854. };
  8855. Tools.ExitFullscreen = function () {
  8856. if (document.exitFullscreen) {
  8857. document.exitFullscreen();
  8858. }
  8859. else if (document.mozCancelFullScreen) {
  8860. document.mozCancelFullScreen();
  8861. }
  8862. else if (document.webkitCancelFullScreen) {
  8863. document.webkitCancelFullScreen();
  8864. }
  8865. else if (document.msCancelFullScreen) {
  8866. document.msCancelFullScreen();
  8867. }
  8868. };
  8869. Tools.SetCorsBehavior = function (url, element) {
  8870. if (url && url.indexOf("data:") === 0) {
  8871. return;
  8872. }
  8873. if (Tools.CorsBehavior) {
  8874. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8875. element.crossOrigin = Tools.CorsBehavior;
  8876. }
  8877. else {
  8878. var result = Tools.CorsBehavior(url);
  8879. if (result) {
  8880. element.crossOrigin = result;
  8881. }
  8882. }
  8883. }
  8884. };
  8885. // External files
  8886. Tools.CleanUrl = function (url) {
  8887. url = url.replace(/#/mg, "%23");
  8888. return url;
  8889. };
  8890. /**
  8891. * Loads an image as an HTMLImageElement.
  8892. * @param input url string, ArrayBuffer, or Blob to load
  8893. * @param onLoad callback called when the image successfully loads
  8894. * @param onError callback called when the image fails to load
  8895. * @param database database for caching
  8896. * @returns the HTMLImageElement of the loaded image
  8897. */
  8898. Tools.LoadImage = function (input, onLoad, onError, database) {
  8899. var url;
  8900. var usingObjectURL = false;
  8901. if (input instanceof ArrayBuffer) {
  8902. url = URL.createObjectURL(new Blob([input]));
  8903. usingObjectURL = true;
  8904. }
  8905. else if (input instanceof Blob) {
  8906. url = URL.createObjectURL(input);
  8907. usingObjectURL = true;
  8908. }
  8909. else {
  8910. url = Tools.CleanUrl(input);
  8911. url = Tools.PreprocessUrl(input);
  8912. }
  8913. var img = new Image();
  8914. Tools.SetCorsBehavior(url, img);
  8915. var loadHandler = function () {
  8916. if (usingObjectURL && img.src) {
  8917. URL.revokeObjectURL(img.src);
  8918. }
  8919. img.removeEventListener("load", loadHandler);
  8920. img.removeEventListener("error", errorHandler);
  8921. onLoad(img);
  8922. };
  8923. var errorHandler = function (err) {
  8924. if (usingObjectURL && img.src) {
  8925. URL.revokeObjectURL(img.src);
  8926. }
  8927. img.removeEventListener("load", loadHandler);
  8928. img.removeEventListener("error", errorHandler);
  8929. Tools.Error("Error while trying to load image: " + input);
  8930. if (onError) {
  8931. onError("Error while trying to load image: " + input, err);
  8932. }
  8933. };
  8934. img.addEventListener("load", loadHandler);
  8935. img.addEventListener("error", errorHandler);
  8936. var noIndexedDB = function () {
  8937. img.src = url;
  8938. };
  8939. var loadFromIndexedDB = function () {
  8940. if (database) {
  8941. database.loadImageFromDB(url, img);
  8942. }
  8943. };
  8944. //ANY database to do!
  8945. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8946. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8947. }
  8948. else {
  8949. if (url.indexOf("file:") !== -1) {
  8950. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8951. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8952. try {
  8953. var blobURL;
  8954. try {
  8955. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8956. }
  8957. catch (ex) {
  8958. // Chrome doesn't support oneTimeOnly parameter
  8959. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8960. }
  8961. img.src = blobURL;
  8962. usingObjectURL = true;
  8963. }
  8964. catch (e) {
  8965. img.src = "";
  8966. }
  8967. return img;
  8968. }
  8969. }
  8970. noIndexedDB();
  8971. }
  8972. return img;
  8973. };
  8974. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8975. url = Tools.CleanUrl(url);
  8976. url = Tools.PreprocessUrl(url);
  8977. // If file and file input are set
  8978. if (url.indexOf("file:") !== -1) {
  8979. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8980. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8981. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8982. }
  8983. }
  8984. var loadUrl = Tools.BaseUrl + url;
  8985. var aborted = false;
  8986. var fileRequest = {
  8987. onCompleteObservable: new BABYLON.Observable(),
  8988. abort: function () { return aborted = true; },
  8989. };
  8990. var requestFile = function () {
  8991. var request = new XMLHttpRequest();
  8992. var retryHandle = null;
  8993. fileRequest.abort = function () {
  8994. aborted = true;
  8995. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8996. request.abort();
  8997. }
  8998. if (retryHandle !== null) {
  8999. clearTimeout(retryHandle);
  9000. retryHandle = null;
  9001. }
  9002. };
  9003. var retryLoop = function (retryIndex) {
  9004. request.open('GET', loadUrl, true);
  9005. if (useArrayBuffer) {
  9006. request.responseType = "arraybuffer";
  9007. }
  9008. if (onProgress) {
  9009. request.addEventListener("progress", onProgress);
  9010. }
  9011. var onLoadEnd = function () {
  9012. request.removeEventListener("loadend", onLoadEnd);
  9013. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9014. fileRequest.onCompleteObservable.clear();
  9015. };
  9016. request.addEventListener("loadend", onLoadEnd);
  9017. var onReadyStateChange = function () {
  9018. if (aborted) {
  9019. return;
  9020. }
  9021. // In case of undefined state in some browsers.
  9022. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9023. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9024. request.removeEventListener("readystatechange", onReadyStateChange);
  9025. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9026. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9027. return;
  9028. }
  9029. var retryStrategy = Tools.DefaultRetryStrategy;
  9030. if (retryStrategy) {
  9031. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9032. if (waitTime !== -1) {
  9033. // Prevent the request from completing for retry.
  9034. request.removeEventListener("loadend", onLoadEnd);
  9035. request = new XMLHttpRequest();
  9036. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9037. return;
  9038. }
  9039. }
  9040. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9041. if (onError) {
  9042. onError(request, e);
  9043. }
  9044. else {
  9045. throw e;
  9046. }
  9047. }
  9048. };
  9049. request.addEventListener("readystatechange", onReadyStateChange);
  9050. request.send();
  9051. };
  9052. retryLoop(0);
  9053. };
  9054. // Caching all files
  9055. if (database && database.enableSceneOffline) {
  9056. var noIndexedDB_1 = function () {
  9057. if (!aborted) {
  9058. requestFile();
  9059. }
  9060. };
  9061. var loadFromIndexedDB = function () {
  9062. // TODO: database needs to support aborting and should return a IFileRequest
  9063. if (aborted) {
  9064. return;
  9065. }
  9066. if (database) {
  9067. database.loadFileFromDB(url, function (data) {
  9068. if (!aborted) {
  9069. onSuccess(data);
  9070. }
  9071. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9072. }, onProgress ? function (event) {
  9073. if (!aborted) {
  9074. onProgress(event);
  9075. }
  9076. } : undefined, noIndexedDB_1, useArrayBuffer);
  9077. }
  9078. };
  9079. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9080. }
  9081. else {
  9082. requestFile();
  9083. }
  9084. return fileRequest;
  9085. };
  9086. /**
  9087. * Load a script (identified by an url). When the url returns, the
  9088. * content of this file is added into a new script element, attached to the DOM (body element)
  9089. */
  9090. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9091. var head = document.getElementsByTagName('head')[0];
  9092. var script = document.createElement('script');
  9093. script.type = 'text/javascript';
  9094. script.src = scriptUrl;
  9095. script.onload = function () {
  9096. if (onSuccess) {
  9097. onSuccess();
  9098. }
  9099. };
  9100. script.onerror = function (e) {
  9101. if (onError) {
  9102. onError("Unable to load script '" + scriptUrl + "'", e);
  9103. }
  9104. };
  9105. head.appendChild(script);
  9106. };
  9107. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9108. var reader = new FileReader();
  9109. var request = {
  9110. onCompleteObservable: new BABYLON.Observable(),
  9111. abort: function () { return reader.abort(); },
  9112. };
  9113. reader.onloadend = function (e) {
  9114. request.onCompleteObservable.notifyObservers(request);
  9115. };
  9116. reader.onload = function (e) {
  9117. //target doesn't have result from ts 1.3
  9118. callback(e.target['result']);
  9119. };
  9120. reader.onprogress = progressCallback;
  9121. reader.readAsDataURL(fileToLoad);
  9122. return request;
  9123. };
  9124. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9125. var reader = new FileReader();
  9126. var request = {
  9127. onCompleteObservable: new BABYLON.Observable(),
  9128. abort: function () { return reader.abort(); },
  9129. };
  9130. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9131. reader.onerror = function (e) {
  9132. Tools.Log("Error while reading file: " + fileToLoad.name);
  9133. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9134. };
  9135. reader.onload = function (e) {
  9136. //target doesn't have result from ts 1.3
  9137. callback(e.target['result']);
  9138. };
  9139. if (progressCallBack) {
  9140. reader.onprogress = progressCallBack;
  9141. }
  9142. if (!useArrayBuffer) {
  9143. // Asynchronous read
  9144. reader.readAsText(fileToLoad);
  9145. }
  9146. else {
  9147. reader.readAsArrayBuffer(fileToLoad);
  9148. }
  9149. return request;
  9150. };
  9151. //returns a downloadable url to a file content.
  9152. Tools.FileAsURL = function (content) {
  9153. var fileBlob = new Blob([content]);
  9154. var url = window.URL || window.webkitURL;
  9155. var link = url.createObjectURL(fileBlob);
  9156. return link;
  9157. };
  9158. // Misc.
  9159. Tools.Format = function (value, decimals) {
  9160. if (decimals === void 0) { decimals = 2; }
  9161. return value.toFixed(decimals);
  9162. };
  9163. Tools.CheckExtends = function (v, min, max) {
  9164. if (v.x < min.x)
  9165. min.x = v.x;
  9166. if (v.y < min.y)
  9167. min.y = v.y;
  9168. if (v.z < min.z)
  9169. min.z = v.z;
  9170. if (v.x > max.x)
  9171. max.x = v.x;
  9172. if (v.y > max.y)
  9173. max.y = v.y;
  9174. if (v.z > max.z)
  9175. max.z = v.z;
  9176. };
  9177. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9178. for (var prop in source) {
  9179. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9180. continue;
  9181. }
  9182. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9183. continue;
  9184. }
  9185. var sourceValue = source[prop];
  9186. var typeOfSourceValue = typeof sourceValue;
  9187. if (typeOfSourceValue === "function") {
  9188. continue;
  9189. }
  9190. try {
  9191. if (typeOfSourceValue === "object") {
  9192. if (sourceValue instanceof Array) {
  9193. destination[prop] = [];
  9194. if (sourceValue.length > 0) {
  9195. if (typeof sourceValue[0] == "object") {
  9196. for (var index = 0; index < sourceValue.length; index++) {
  9197. var clonedValue = cloneValue(sourceValue[index], destination);
  9198. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9199. destination[prop].push(clonedValue);
  9200. }
  9201. }
  9202. }
  9203. else {
  9204. destination[prop] = sourceValue.slice(0);
  9205. }
  9206. }
  9207. }
  9208. else {
  9209. destination[prop] = cloneValue(sourceValue, destination);
  9210. }
  9211. }
  9212. else {
  9213. destination[prop] = sourceValue;
  9214. }
  9215. }
  9216. catch (e) {
  9217. // Just ignore error (it could be because of a read-only property)
  9218. }
  9219. }
  9220. };
  9221. Tools.IsEmpty = function (obj) {
  9222. for (var i in obj) {
  9223. if (obj.hasOwnProperty(i)) {
  9224. return false;
  9225. }
  9226. }
  9227. return true;
  9228. };
  9229. Tools.RegisterTopRootEvents = function (events) {
  9230. for (var index = 0; index < events.length; index++) {
  9231. var event = events[index];
  9232. window.addEventListener(event.name, event.handler, false);
  9233. try {
  9234. if (window.parent) {
  9235. window.parent.addEventListener(event.name, event.handler, false);
  9236. }
  9237. }
  9238. catch (e) {
  9239. // Silently fails...
  9240. }
  9241. }
  9242. };
  9243. Tools.UnregisterTopRootEvents = function (events) {
  9244. for (var index = 0; index < events.length; index++) {
  9245. var event = events[index];
  9246. window.removeEventListener(event.name, event.handler);
  9247. try {
  9248. if (window.parent) {
  9249. window.parent.removeEventListener(event.name, event.handler);
  9250. }
  9251. }
  9252. catch (e) {
  9253. // Silently fails...
  9254. }
  9255. }
  9256. };
  9257. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9258. if (mimeType === void 0) { mimeType = "image/png"; }
  9259. // Read the contents of the framebuffer
  9260. var numberOfChannelsByLine = width * 4;
  9261. var halfHeight = height / 2;
  9262. //Reading datas from WebGL
  9263. var data = engine.readPixels(0, 0, width, height);
  9264. //To flip image on Y axis.
  9265. for (var i = 0; i < halfHeight; i++) {
  9266. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9267. var currentCell = j + i * numberOfChannelsByLine;
  9268. var targetLine = height - i - 1;
  9269. var targetCell = j + targetLine * numberOfChannelsByLine;
  9270. var temp = data[currentCell];
  9271. data[currentCell] = data[targetCell];
  9272. data[targetCell] = temp;
  9273. }
  9274. }
  9275. // Create a 2D canvas to store the result
  9276. if (!screenshotCanvas) {
  9277. screenshotCanvas = document.createElement('canvas');
  9278. }
  9279. screenshotCanvas.width = width;
  9280. screenshotCanvas.height = height;
  9281. var context = screenshotCanvas.getContext('2d');
  9282. if (context) {
  9283. // Copy the pixels to a 2D canvas
  9284. var imageData = context.createImageData(width, height);
  9285. var castData = (imageData.data);
  9286. castData.set(data);
  9287. context.putImageData(imageData, 0, 0);
  9288. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9289. }
  9290. };
  9291. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9292. if (mimeType === void 0) { mimeType = "image/png"; }
  9293. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9294. if (successCallback) {
  9295. successCallback(base64Image);
  9296. }
  9297. else {
  9298. // We need HTMLCanvasElement.toBlob for HD screenshots
  9299. if (!screenshotCanvas.toBlob) {
  9300. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9301. screenshotCanvas.toBlob = function (callback, type, quality) {
  9302. var _this = this;
  9303. setTimeout(function () {
  9304. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9305. for (var i = 0; i < len; i++) {
  9306. arr[i] = binStr.charCodeAt(i);
  9307. }
  9308. callback(new Blob([arr], { type: type || 'image/png' }));
  9309. });
  9310. };
  9311. }
  9312. screenshotCanvas.toBlob(function (blob) {
  9313. var url = URL.createObjectURL(blob);
  9314. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9315. if (("download" in document.createElement("a"))) {
  9316. var a = window.document.createElement("a");
  9317. a.href = url;
  9318. if (fileName) {
  9319. a.setAttribute("download", fileName);
  9320. }
  9321. else {
  9322. var date = new Date();
  9323. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9324. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9325. }
  9326. window.document.body.appendChild(a);
  9327. a.addEventListener("click", function () {
  9328. if (a.parentElement) {
  9329. a.parentElement.removeChild(a);
  9330. }
  9331. });
  9332. a.click();
  9333. }
  9334. else {
  9335. var newWindow = window.open("");
  9336. if (!newWindow)
  9337. return;
  9338. var img = newWindow.document.createElement("img");
  9339. img.onload = function () {
  9340. // no longer need to read the blob so it's revoked
  9341. URL.revokeObjectURL(url);
  9342. };
  9343. img.src = url;
  9344. newWindow.document.body.appendChild(img);
  9345. }
  9346. });
  9347. }
  9348. };
  9349. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9350. if (mimeType === void 0) { mimeType = "image/png"; }
  9351. var width;
  9352. var height;
  9353. // If a precision value is specified
  9354. if (size.precision) {
  9355. width = Math.round(engine.getRenderWidth() * size.precision);
  9356. height = Math.round(width / engine.getAspectRatio(camera));
  9357. }
  9358. else if (size.width && size.height) {
  9359. width = size.width;
  9360. height = size.height;
  9361. }
  9362. //If passing only width, computing height to keep display canvas ratio.
  9363. else if (size.width && !size.height) {
  9364. width = size.width;
  9365. height = Math.round(width / engine.getAspectRatio(camera));
  9366. }
  9367. //If passing only height, computing width to keep display canvas ratio.
  9368. else if (size.height && !size.width) {
  9369. height = size.height;
  9370. width = Math.round(height * engine.getAspectRatio(camera));
  9371. }
  9372. //Assuming here that "size" parameter is a number
  9373. else if (!isNaN(size)) {
  9374. height = size;
  9375. width = size;
  9376. }
  9377. else {
  9378. Tools.Error("Invalid 'size' parameter !");
  9379. return;
  9380. }
  9381. if (!screenshotCanvas) {
  9382. screenshotCanvas = document.createElement('canvas');
  9383. }
  9384. screenshotCanvas.width = width;
  9385. screenshotCanvas.height = height;
  9386. var renderContext = screenshotCanvas.getContext("2d");
  9387. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9388. var newWidth = width;
  9389. var newHeight = newWidth / ratio;
  9390. if (newHeight > height) {
  9391. newHeight = height;
  9392. newWidth = newHeight * ratio;
  9393. }
  9394. var offsetX = Math.max(0, width - newWidth) / 2;
  9395. var offsetY = Math.max(0, height - newHeight) / 2;
  9396. var renderingCanvas = engine.getRenderingCanvas();
  9397. if (renderContext && renderingCanvas) {
  9398. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9399. }
  9400. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9401. };
  9402. /**
  9403. * Generates an image screenshot from the specified camera.
  9404. *
  9405. * @param engine The engine to use for rendering
  9406. * @param camera The camera to use for rendering
  9407. * @param size This parameter can be set to a single number or to an object with the
  9408. * following (optional) properties: precision, width, height. If a single number is passed,
  9409. * it will be used for both width and height. If an object is passed, the screenshot size
  9410. * will be derived from the parameters. The precision property is a multiplier allowing
  9411. * rendering at a higher or lower resolution.
  9412. * @param successCallback The callback receives a single parameter which contains the
  9413. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9414. * src parameter of an <img> to display it.
  9415. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9416. * Check your browser for supported MIME types.
  9417. * @param samples Texture samples (default: 1)
  9418. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9419. * @param fileName A name for for the downloaded file.
  9420. * @constructor
  9421. */
  9422. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9423. if (mimeType === void 0) { mimeType = "image/png"; }
  9424. if (samples === void 0) { samples = 1; }
  9425. if (antialiasing === void 0) { antialiasing = false; }
  9426. var width;
  9427. var height;
  9428. //If a precision value is specified
  9429. if (size.precision) {
  9430. width = Math.round(engine.getRenderWidth() * size.precision);
  9431. height = Math.round(width / engine.getAspectRatio(camera));
  9432. size = { width: width, height: height };
  9433. }
  9434. else if (size.width && size.height) {
  9435. width = size.width;
  9436. height = size.height;
  9437. }
  9438. //If passing only width, computing height to keep display canvas ratio.
  9439. else if (size.width && !size.height) {
  9440. width = size.width;
  9441. height = Math.round(width / engine.getAspectRatio(camera));
  9442. size = { width: width, height: height };
  9443. }
  9444. //If passing only height, computing width to keep display canvas ratio.
  9445. else if (size.height && !size.width) {
  9446. height = size.height;
  9447. width = Math.round(height * engine.getAspectRatio(camera));
  9448. size = { width: width, height: height };
  9449. }
  9450. //Assuming here that "size" parameter is a number
  9451. else if (!isNaN(size)) {
  9452. height = size;
  9453. width = size;
  9454. }
  9455. else {
  9456. Tools.Error("Invalid 'size' parameter !");
  9457. return;
  9458. }
  9459. var scene = camera.getScene();
  9460. var previousCamera = null;
  9461. if (scene.activeCamera !== camera) {
  9462. previousCamera = scene.activeCamera;
  9463. scene.activeCamera = camera;
  9464. }
  9465. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9466. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9467. texture.renderList = null;
  9468. texture.samples = samples;
  9469. if (antialiasing) {
  9470. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9471. }
  9472. texture.onAfterRenderObservable.add(function () {
  9473. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9474. });
  9475. scene.incrementRenderId();
  9476. scene.resetCachedMaterial();
  9477. texture.render(true);
  9478. texture.dispose();
  9479. if (previousCamera) {
  9480. scene.activeCamera = previousCamera;
  9481. }
  9482. camera.getProjectionMatrix(true); // Force cache refresh;
  9483. };
  9484. // XHR response validator for local file scenario
  9485. Tools.ValidateXHRData = function (xhr, dataType) {
  9486. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9487. if (dataType === void 0) { dataType = 7; }
  9488. try {
  9489. if (dataType & 1) {
  9490. if (xhr.responseText && xhr.responseText.length > 0) {
  9491. return true;
  9492. }
  9493. else if (dataType === 1) {
  9494. return false;
  9495. }
  9496. }
  9497. if (dataType & 2) {
  9498. // Check header width and height since there is no "TGA" magic number
  9499. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9500. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9501. return true;
  9502. }
  9503. else if (dataType === 2) {
  9504. return false;
  9505. }
  9506. }
  9507. if (dataType & 4) {
  9508. // Check for the "DDS" magic number
  9509. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9510. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9511. return true;
  9512. }
  9513. else {
  9514. return false;
  9515. }
  9516. }
  9517. }
  9518. catch (e) {
  9519. // Global protection
  9520. }
  9521. return false;
  9522. };
  9523. /**
  9524. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9525. * Be aware Math.random() could cause collisions, but:
  9526. * "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"
  9527. */
  9528. Tools.RandomId = function () {
  9529. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9530. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9531. return v.toString(16);
  9532. });
  9533. };
  9534. /**
  9535. * Test if the given uri is a base64 string.
  9536. * @param uri The uri to test
  9537. * @return True if the uri is a base64 string or false otherwise.
  9538. */
  9539. Tools.IsBase64 = function (uri) {
  9540. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9541. };
  9542. /**
  9543. * Decode the given base64 uri.
  9544. * @param uri The uri to decode
  9545. * @return The decoded base64 data.
  9546. */
  9547. Tools.DecodeBase64 = function (uri) {
  9548. var decodedString = atob(uri.split(",")[1]);
  9549. var bufferLength = decodedString.length;
  9550. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9551. for (var i = 0; i < bufferLength; i++) {
  9552. bufferView[i] = decodedString.charCodeAt(i);
  9553. }
  9554. return bufferView.buffer;
  9555. };
  9556. Object.defineProperty(Tools, "NoneLogLevel", {
  9557. get: function () {
  9558. return Tools._NoneLogLevel;
  9559. },
  9560. enumerable: true,
  9561. configurable: true
  9562. });
  9563. Object.defineProperty(Tools, "MessageLogLevel", {
  9564. get: function () {
  9565. return Tools._MessageLogLevel;
  9566. },
  9567. enumerable: true,
  9568. configurable: true
  9569. });
  9570. Object.defineProperty(Tools, "WarningLogLevel", {
  9571. get: function () {
  9572. return Tools._WarningLogLevel;
  9573. },
  9574. enumerable: true,
  9575. configurable: true
  9576. });
  9577. Object.defineProperty(Tools, "ErrorLogLevel", {
  9578. get: function () {
  9579. return Tools._ErrorLogLevel;
  9580. },
  9581. enumerable: true,
  9582. configurable: true
  9583. });
  9584. Object.defineProperty(Tools, "AllLogLevel", {
  9585. get: function () {
  9586. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9587. },
  9588. enumerable: true,
  9589. configurable: true
  9590. });
  9591. Tools._AddLogEntry = function (entry) {
  9592. Tools._LogCache = entry + Tools._LogCache;
  9593. if (Tools.OnNewCacheEntry) {
  9594. Tools.OnNewCacheEntry(entry);
  9595. }
  9596. };
  9597. Tools._FormatMessage = function (message) {
  9598. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9599. var date = new Date();
  9600. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9601. };
  9602. Tools._LogDisabled = function (message) {
  9603. // nothing to do
  9604. };
  9605. Tools._LogEnabled = function (message) {
  9606. var formattedMessage = Tools._FormatMessage(message);
  9607. console.log("BJS - " + formattedMessage);
  9608. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9609. Tools._AddLogEntry(entry);
  9610. };
  9611. Tools._WarnDisabled = function (message) {
  9612. // nothing to do
  9613. };
  9614. Tools._WarnEnabled = function (message) {
  9615. var formattedMessage = Tools._FormatMessage(message);
  9616. console.warn("BJS - " + formattedMessage);
  9617. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9618. Tools._AddLogEntry(entry);
  9619. };
  9620. Tools._ErrorDisabled = function (message) {
  9621. // nothing to do
  9622. };
  9623. Tools._ErrorEnabled = function (message) {
  9624. Tools.errorsCount++;
  9625. var formattedMessage = Tools._FormatMessage(message);
  9626. console.error("BJS - " + formattedMessage);
  9627. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9628. Tools._AddLogEntry(entry);
  9629. };
  9630. Object.defineProperty(Tools, "LogCache", {
  9631. get: function () {
  9632. return Tools._LogCache;
  9633. },
  9634. enumerable: true,
  9635. configurable: true
  9636. });
  9637. Tools.ClearLogCache = function () {
  9638. Tools._LogCache = "";
  9639. Tools.errorsCount = 0;
  9640. };
  9641. Object.defineProperty(Tools, "LogLevels", {
  9642. set: function (level) {
  9643. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9644. Tools.Log = Tools._LogEnabled;
  9645. }
  9646. else {
  9647. Tools.Log = Tools._LogDisabled;
  9648. }
  9649. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9650. Tools.Warn = Tools._WarnEnabled;
  9651. }
  9652. else {
  9653. Tools.Warn = Tools._WarnDisabled;
  9654. }
  9655. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9656. Tools.Error = Tools._ErrorEnabled;
  9657. }
  9658. else {
  9659. Tools.Error = Tools._ErrorDisabled;
  9660. }
  9661. },
  9662. enumerable: true,
  9663. configurable: true
  9664. });
  9665. Tools.IsWindowObjectExist = function () {
  9666. return (typeof window) !== "undefined";
  9667. };
  9668. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9669. get: function () {
  9670. return Tools._PerformanceNoneLogLevel;
  9671. },
  9672. enumerable: true,
  9673. configurable: true
  9674. });
  9675. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9676. get: function () {
  9677. return Tools._PerformanceUserMarkLogLevel;
  9678. },
  9679. enumerable: true,
  9680. configurable: true
  9681. });
  9682. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9683. get: function () {
  9684. return Tools._PerformanceConsoleLogLevel;
  9685. },
  9686. enumerable: true,
  9687. configurable: true
  9688. });
  9689. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9690. set: function (level) {
  9691. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9692. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9693. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9694. return;
  9695. }
  9696. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9697. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9698. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9699. return;
  9700. }
  9701. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9702. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9703. },
  9704. enumerable: true,
  9705. configurable: true
  9706. });
  9707. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9708. };
  9709. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9710. };
  9711. Tools._StartUserMark = function (counterName, condition) {
  9712. if (condition === void 0) { condition = true; }
  9713. if (!Tools._performance) {
  9714. if (!Tools.IsWindowObjectExist()) {
  9715. return;
  9716. }
  9717. Tools._performance = window.performance;
  9718. }
  9719. if (!condition || !Tools._performance.mark) {
  9720. return;
  9721. }
  9722. Tools._performance.mark(counterName + "-Begin");
  9723. };
  9724. Tools._EndUserMark = function (counterName, condition) {
  9725. if (condition === void 0) { condition = true; }
  9726. if (!condition || !Tools._performance.mark) {
  9727. return;
  9728. }
  9729. Tools._performance.mark(counterName + "-End");
  9730. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9731. };
  9732. Tools._StartPerformanceConsole = function (counterName, condition) {
  9733. if (condition === void 0) { condition = true; }
  9734. if (!condition) {
  9735. return;
  9736. }
  9737. Tools._StartUserMark(counterName, condition);
  9738. if (console.time) {
  9739. console.time(counterName);
  9740. }
  9741. };
  9742. Tools._EndPerformanceConsole = function (counterName, condition) {
  9743. if (condition === void 0) { condition = true; }
  9744. if (!condition) {
  9745. return;
  9746. }
  9747. Tools._EndUserMark(counterName, condition);
  9748. if (console.time) {
  9749. console.timeEnd(counterName);
  9750. }
  9751. };
  9752. Object.defineProperty(Tools, "Now", {
  9753. get: function () {
  9754. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9755. return window.performance.now();
  9756. }
  9757. return Date.now();
  9758. },
  9759. enumerable: true,
  9760. configurable: true
  9761. });
  9762. /**
  9763. * This method will return the name of the class used to create the instance of the given object.
  9764. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9765. * @param object the object to get the class name from
  9766. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9767. */
  9768. Tools.GetClassName = function (object, isType) {
  9769. if (isType === void 0) { isType = false; }
  9770. var name = null;
  9771. if (!isType && object.getClassName) {
  9772. name = object.getClassName();
  9773. }
  9774. else {
  9775. if (object instanceof Object) {
  9776. var classObj = isType ? object : Object.getPrototypeOf(object);
  9777. name = classObj.constructor["__bjsclassName__"];
  9778. }
  9779. if (!name) {
  9780. name = typeof object;
  9781. }
  9782. }
  9783. return name;
  9784. };
  9785. Tools.First = function (array, predicate) {
  9786. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9787. var el = array_1[_i];
  9788. if (predicate(el)) {
  9789. return el;
  9790. }
  9791. }
  9792. return null;
  9793. };
  9794. /**
  9795. * This method will return the name of the full name of the class, including its owning module (if any).
  9796. * 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).
  9797. * @param object the object to get the class name from
  9798. * @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.
  9799. */
  9800. Tools.getFullClassName = function (object, isType) {
  9801. if (isType === void 0) { isType = false; }
  9802. var className = null;
  9803. var moduleName = null;
  9804. if (!isType && object.getClassName) {
  9805. className = object.getClassName();
  9806. }
  9807. else {
  9808. if (object instanceof Object) {
  9809. var classObj = isType ? object : Object.getPrototypeOf(object);
  9810. className = classObj.constructor["__bjsclassName__"];
  9811. moduleName = classObj.constructor["__bjsmoduleName__"];
  9812. }
  9813. if (!className) {
  9814. className = typeof object;
  9815. }
  9816. }
  9817. if (!className) {
  9818. return null;
  9819. }
  9820. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9821. };
  9822. /**
  9823. * 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.
  9824. * @param array
  9825. */
  9826. Tools.arrayOrStringFeeder = function (array) {
  9827. return function (index) {
  9828. if (index >= array.length) {
  9829. return null;
  9830. }
  9831. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9832. if (val && val.getHashCode) {
  9833. val = val.getHashCode();
  9834. }
  9835. if (typeof val === "string") {
  9836. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9837. }
  9838. return val;
  9839. };
  9840. };
  9841. /**
  9842. * Compute the hashCode of a stream of number
  9843. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9844. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9845. * @return the hash code computed
  9846. */
  9847. Tools.hashCodeFromStream = function (feeder) {
  9848. // Based from here: http://stackoverflow.com/a/7616484/802124
  9849. var hash = 0;
  9850. var index = 0;
  9851. var chr = feeder(index++);
  9852. while (chr != null) {
  9853. hash = ((hash << 5) - hash) + chr;
  9854. hash |= 0; // Convert to 32bit integer
  9855. chr = feeder(index++);
  9856. }
  9857. return hash;
  9858. };
  9859. /**
  9860. * Returns a promise that resolves after the given amount of time.
  9861. * @param delay Number of milliseconds to delay
  9862. * @returns Promise that resolves after the given amount of time
  9863. */
  9864. Tools.DelayAsync = function (delay) {
  9865. return new Promise(function (resolve) {
  9866. setTimeout(function () {
  9867. resolve();
  9868. }, delay);
  9869. });
  9870. };
  9871. Tools.BaseUrl = "";
  9872. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9873. /**
  9874. * Default behaviour for cors in the application.
  9875. * It can be a string if the expected behavior is identical in the entire app.
  9876. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9877. */
  9878. Tools.CorsBehavior = "anonymous";
  9879. Tools.UseFallbackTexture = true;
  9880. /**
  9881. * Use this object to register external classes like custom textures or material
  9882. * to allow the laoders to instantiate them
  9883. */
  9884. Tools.RegisteredExternalClasses = {};
  9885. // Used in case of a texture loading problem
  9886. 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";
  9887. Tools._tmpFloatArray = new Float32Array(1);
  9888. Tools.PreprocessUrl = function (url) {
  9889. return url;
  9890. };
  9891. // Logs
  9892. Tools._NoneLogLevel = 0;
  9893. Tools._MessageLogLevel = 1;
  9894. Tools._WarningLogLevel = 2;
  9895. Tools._ErrorLogLevel = 4;
  9896. Tools._LogCache = "";
  9897. Tools.errorsCount = 0;
  9898. Tools.Log = Tools._LogEnabled;
  9899. Tools.Warn = Tools._WarnEnabled;
  9900. Tools.Error = Tools._ErrorEnabled;
  9901. // Performances
  9902. Tools._PerformanceNoneLogLevel = 0;
  9903. Tools._PerformanceUserMarkLogLevel = 1;
  9904. Tools._PerformanceConsoleLogLevel = 2;
  9905. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9906. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9907. return Tools;
  9908. }());
  9909. BABYLON.Tools = Tools;
  9910. /**
  9911. * This class is used to track a performance counter which is number based.
  9912. * The user has access to many properties which give statistics of different nature
  9913. *
  9914. * The implementer can track two kinds of Performance Counter: time and count
  9915. * 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.
  9916. * 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.
  9917. */
  9918. var PerfCounter = /** @class */ (function () {
  9919. function PerfCounter() {
  9920. this._startMonitoringTime = 0;
  9921. this._min = 0;
  9922. this._max = 0;
  9923. this._average = 0;
  9924. this._lastSecAverage = 0;
  9925. this._current = 0;
  9926. this._totalValueCount = 0;
  9927. this._totalAccumulated = 0;
  9928. this._lastSecAccumulated = 0;
  9929. this._lastSecTime = 0;
  9930. this._lastSecValueCount = 0;
  9931. }
  9932. Object.defineProperty(PerfCounter.prototype, "min", {
  9933. /**
  9934. * Returns the smallest value ever
  9935. */
  9936. get: function () {
  9937. return this._min;
  9938. },
  9939. enumerable: true,
  9940. configurable: true
  9941. });
  9942. Object.defineProperty(PerfCounter.prototype, "max", {
  9943. /**
  9944. * Returns the biggest value ever
  9945. */
  9946. get: function () {
  9947. return this._max;
  9948. },
  9949. enumerable: true,
  9950. configurable: true
  9951. });
  9952. Object.defineProperty(PerfCounter.prototype, "average", {
  9953. /**
  9954. * Returns the average value since the performance counter is running
  9955. */
  9956. get: function () {
  9957. return this._average;
  9958. },
  9959. enumerable: true,
  9960. configurable: true
  9961. });
  9962. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9963. /**
  9964. * Returns the average value of the last second the counter was monitored
  9965. */
  9966. get: function () {
  9967. return this._lastSecAverage;
  9968. },
  9969. enumerable: true,
  9970. configurable: true
  9971. });
  9972. Object.defineProperty(PerfCounter.prototype, "current", {
  9973. /**
  9974. * Returns the current value
  9975. */
  9976. get: function () {
  9977. return this._current;
  9978. },
  9979. enumerable: true,
  9980. configurable: true
  9981. });
  9982. Object.defineProperty(PerfCounter.prototype, "total", {
  9983. get: function () {
  9984. return this._totalAccumulated;
  9985. },
  9986. enumerable: true,
  9987. configurable: true
  9988. });
  9989. Object.defineProperty(PerfCounter.prototype, "count", {
  9990. get: function () {
  9991. return this._totalValueCount;
  9992. },
  9993. enumerable: true,
  9994. configurable: true
  9995. });
  9996. /**
  9997. * Call this method to start monitoring a new frame.
  9998. * 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.
  9999. */
  10000. PerfCounter.prototype.fetchNewFrame = function () {
  10001. this._totalValueCount++;
  10002. this._current = 0;
  10003. this._lastSecValueCount++;
  10004. };
  10005. /**
  10006. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10007. * @param newCount the count value to add to the monitored count
  10008. * @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.
  10009. */
  10010. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10011. if (!PerfCounter.Enabled) {
  10012. return;
  10013. }
  10014. this._current += newCount;
  10015. if (fetchResult) {
  10016. this._fetchResult();
  10017. }
  10018. };
  10019. /**
  10020. * Start monitoring this performance counter
  10021. */
  10022. PerfCounter.prototype.beginMonitoring = function () {
  10023. if (!PerfCounter.Enabled) {
  10024. return;
  10025. }
  10026. this._startMonitoringTime = Tools.Now;
  10027. };
  10028. /**
  10029. * Compute the time lapsed since the previous beginMonitoring() call.
  10030. * @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
  10031. */
  10032. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10033. if (newFrame === void 0) { newFrame = true; }
  10034. if (!PerfCounter.Enabled) {
  10035. return;
  10036. }
  10037. if (newFrame) {
  10038. this.fetchNewFrame();
  10039. }
  10040. var currentTime = Tools.Now;
  10041. this._current = currentTime - this._startMonitoringTime;
  10042. if (newFrame) {
  10043. this._fetchResult();
  10044. }
  10045. };
  10046. PerfCounter.prototype._fetchResult = function () {
  10047. this._totalAccumulated += this._current;
  10048. this._lastSecAccumulated += this._current;
  10049. // Min/Max update
  10050. this._min = Math.min(this._min, this._current);
  10051. this._max = Math.max(this._max, this._current);
  10052. this._average = this._totalAccumulated / this._totalValueCount;
  10053. // Reset last sec?
  10054. var now = Tools.Now;
  10055. if ((now - this._lastSecTime) > 1000) {
  10056. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10057. this._lastSecTime = now;
  10058. this._lastSecAccumulated = 0;
  10059. this._lastSecValueCount = 0;
  10060. }
  10061. };
  10062. PerfCounter.Enabled = true;
  10063. return PerfCounter;
  10064. }());
  10065. BABYLON.PerfCounter = PerfCounter;
  10066. /**
  10067. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10068. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10069. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10070. * @param name The name of the class, case should be preserved
  10071. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10072. */
  10073. function className(name, module) {
  10074. return function (target) {
  10075. target["__bjsclassName__"] = name;
  10076. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10077. };
  10078. }
  10079. BABYLON.className = className;
  10080. /**
  10081. * An implementation of a loop for asynchronous functions.
  10082. */
  10083. var AsyncLoop = /** @class */ (function () {
  10084. /**
  10085. * Constroctor.
  10086. * @param iterations the number of iterations.
  10087. * @param _fn the function to run each iteration
  10088. * @param _successCallback the callback that will be called upon succesful execution
  10089. * @param offset starting offset.
  10090. */
  10091. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10092. if (offset === void 0) { offset = 0; }
  10093. this.iterations = iterations;
  10094. this._fn = _fn;
  10095. this._successCallback = _successCallback;
  10096. this.index = offset - 1;
  10097. this._done = false;
  10098. }
  10099. /**
  10100. * Execute the next iteration. Must be called after the last iteration was finished.
  10101. */
  10102. AsyncLoop.prototype.executeNext = function () {
  10103. if (!this._done) {
  10104. if (this.index + 1 < this.iterations) {
  10105. ++this.index;
  10106. this._fn(this);
  10107. }
  10108. else {
  10109. this.breakLoop();
  10110. }
  10111. }
  10112. };
  10113. /**
  10114. * Break the loop and run the success callback.
  10115. */
  10116. AsyncLoop.prototype.breakLoop = function () {
  10117. this._done = true;
  10118. this._successCallback();
  10119. };
  10120. /**
  10121. * Helper function
  10122. */
  10123. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10124. if (offset === void 0) { offset = 0; }
  10125. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10126. loop.executeNext();
  10127. return loop;
  10128. };
  10129. /**
  10130. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10131. * @param iterations total number of iterations
  10132. * @param syncedIterations number of synchronous iterations in each async iteration.
  10133. * @param fn the function to call each iteration.
  10134. * @param callback a success call back that will be called when iterating stops.
  10135. * @param breakFunction a break condition (optional)
  10136. * @param timeout timeout settings for the setTimeout function. default - 0.
  10137. * @constructor
  10138. */
  10139. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10140. if (timeout === void 0) { timeout = 0; }
  10141. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10142. if (breakFunction && breakFunction())
  10143. loop.breakLoop();
  10144. else {
  10145. setTimeout(function () {
  10146. for (var i = 0; i < syncedIterations; ++i) {
  10147. var iteration = (loop.index * syncedIterations) + i;
  10148. if (iteration >= iterations)
  10149. break;
  10150. fn(iteration);
  10151. if (breakFunction && breakFunction()) {
  10152. loop.breakLoop();
  10153. break;
  10154. }
  10155. }
  10156. loop.executeNext();
  10157. }, timeout);
  10158. }
  10159. }, callback);
  10160. };
  10161. return AsyncLoop;
  10162. }());
  10163. BABYLON.AsyncLoop = AsyncLoop;
  10164. })(BABYLON || (BABYLON = {}));
  10165. //# sourceMappingURL=babylon.tools.js.map
  10166. var BABYLON;
  10167. (function (BABYLON) {
  10168. var PromiseStates;
  10169. (function (PromiseStates) {
  10170. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10171. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10172. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10173. })(PromiseStates || (PromiseStates = {}));
  10174. var FulFillmentAgregator = /** @class */ (function () {
  10175. function FulFillmentAgregator() {
  10176. this.count = 0;
  10177. this.target = 0;
  10178. this.results = [];
  10179. }
  10180. return FulFillmentAgregator;
  10181. }());
  10182. var InternalPromise = /** @class */ (function () {
  10183. function InternalPromise(resolver) {
  10184. var _this = this;
  10185. this._state = PromiseStates.Pending;
  10186. this._children = new Array();
  10187. this._rejectWasConsumed = false;
  10188. if (!resolver) {
  10189. return;
  10190. }
  10191. try {
  10192. resolver(function (value) {
  10193. _this._resolve(value);
  10194. }, function (reason) {
  10195. _this._reject(reason);
  10196. });
  10197. }
  10198. catch (e) {
  10199. this._reject(e);
  10200. }
  10201. }
  10202. Object.defineProperty(InternalPromise.prototype, "_result", {
  10203. get: function () {
  10204. return this._resultValue;
  10205. },
  10206. set: function (value) {
  10207. this._resultValue = value;
  10208. if (this._parent && this._parent._result === undefined) {
  10209. this._parent._result = value;
  10210. }
  10211. },
  10212. enumerable: true,
  10213. configurable: true
  10214. });
  10215. InternalPromise.prototype.catch = function (onRejected) {
  10216. return this.then(undefined, onRejected);
  10217. };
  10218. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10219. var _this = this;
  10220. var newPromise = new InternalPromise();
  10221. newPromise._onFulfilled = onFulfilled;
  10222. newPromise._onRejected = onRejected;
  10223. // Composition
  10224. this._children.push(newPromise);
  10225. newPromise._parent = this;
  10226. if (this._state !== PromiseStates.Pending) {
  10227. BABYLON.Tools.SetImmediate(function () {
  10228. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10229. var returnedValue = newPromise._resolve(_this._result);
  10230. if (returnedValue !== undefined && returnedValue !== null) {
  10231. if (returnedValue._state !== undefined) {
  10232. var returnedPromise = returnedValue;
  10233. newPromise._children.push(returnedPromise);
  10234. returnedPromise._parent = newPromise;
  10235. newPromise = returnedPromise;
  10236. }
  10237. else {
  10238. newPromise._result = returnedValue;
  10239. }
  10240. }
  10241. }
  10242. else {
  10243. newPromise._reject(_this._reason);
  10244. }
  10245. });
  10246. }
  10247. return newPromise;
  10248. };
  10249. InternalPromise.prototype._moveChildren = function (children) {
  10250. var _this = this;
  10251. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10252. this._children.forEach(function (child) {
  10253. child._parent = _this;
  10254. });
  10255. if (this._state === PromiseStates.Fulfilled) {
  10256. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10257. var child = _b[_i];
  10258. child._resolve(this._result);
  10259. }
  10260. }
  10261. else if (this._state === PromiseStates.Rejected) {
  10262. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10263. var child = _d[_c];
  10264. child._reject(this._reason);
  10265. }
  10266. }
  10267. var _a;
  10268. };
  10269. InternalPromise.prototype._resolve = function (value) {
  10270. try {
  10271. this._state = PromiseStates.Fulfilled;
  10272. var returnedValue = null;
  10273. if (this._onFulfilled) {
  10274. returnedValue = this._onFulfilled(value);
  10275. }
  10276. if (returnedValue !== undefined && returnedValue !== null) {
  10277. if (returnedValue._state !== undefined) {
  10278. // Transmit children
  10279. var returnedPromise = returnedValue;
  10280. returnedPromise._parent = this;
  10281. returnedPromise._moveChildren(this._children);
  10282. value = returnedPromise._result;
  10283. }
  10284. else {
  10285. value = returnedValue;
  10286. }
  10287. }
  10288. this._result = value;
  10289. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10290. var child = _a[_i];
  10291. child._resolve(value);
  10292. }
  10293. this._children.length = 0;
  10294. delete this._onFulfilled;
  10295. delete this._onRejected;
  10296. }
  10297. catch (e) {
  10298. this._reject(e, true);
  10299. }
  10300. };
  10301. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10302. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10303. this._state = PromiseStates.Rejected;
  10304. this._reason = reason;
  10305. if (this._onRejected && !onLocalThrow) {
  10306. try {
  10307. this._onRejected(reason);
  10308. this._rejectWasConsumed = true;
  10309. }
  10310. catch (e) {
  10311. reason = e;
  10312. }
  10313. }
  10314. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10315. var child = _a[_i];
  10316. if (this._rejectWasConsumed) {
  10317. child._resolve(null);
  10318. }
  10319. else {
  10320. child._reject(reason);
  10321. }
  10322. }
  10323. this._children.length = 0;
  10324. delete this._onFulfilled;
  10325. delete this._onRejected;
  10326. };
  10327. InternalPromise.resolve = function (value) {
  10328. var newPromise = new InternalPromise();
  10329. newPromise._resolve(value);
  10330. return newPromise;
  10331. };
  10332. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10333. promise.then(function (value) {
  10334. agregator.results[index] = value;
  10335. agregator.count++;
  10336. if (agregator.count === agregator.target) {
  10337. agregator.rootPromise._resolve(agregator.results);
  10338. }
  10339. return null;
  10340. }, function (reason) {
  10341. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10342. agregator.rootPromise._reject(reason);
  10343. }
  10344. });
  10345. };
  10346. InternalPromise.all = function (promises) {
  10347. var newPromise = new InternalPromise();
  10348. var agregator = new FulFillmentAgregator();
  10349. agregator.target = promises.length;
  10350. agregator.rootPromise = newPromise;
  10351. if (promises.length) {
  10352. for (var index = 0; index < promises.length; index++) {
  10353. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10354. }
  10355. }
  10356. else {
  10357. newPromise._resolve([]);
  10358. }
  10359. return newPromise;
  10360. };
  10361. InternalPromise.race = function (promises) {
  10362. var newPromise = new InternalPromise();
  10363. if (promises.length) {
  10364. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10365. var promise = promises_1[_i];
  10366. promise.then(function (value) {
  10367. if (newPromise) {
  10368. newPromise._resolve(value);
  10369. newPromise = null;
  10370. }
  10371. return null;
  10372. }, function (reason) {
  10373. if (newPromise) {
  10374. newPromise._reject(reason);
  10375. newPromise = null;
  10376. }
  10377. });
  10378. }
  10379. }
  10380. return newPromise;
  10381. };
  10382. return InternalPromise;
  10383. }());
  10384. /**
  10385. * Helper class that provides a small promise polyfill
  10386. */
  10387. var PromisePolyfill = /** @class */ (function () {
  10388. function PromisePolyfill() {
  10389. }
  10390. /**
  10391. * Static function used to check if the polyfill is required
  10392. * If this is the case then the function will inject the polyfill to window.Promise
  10393. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10394. */
  10395. PromisePolyfill.Apply = function (force) {
  10396. if (force === void 0) { force = false; }
  10397. if (force || typeof Promise === 'undefined') {
  10398. var root = window;
  10399. root.Promise = InternalPromise;
  10400. }
  10401. };
  10402. return PromisePolyfill;
  10403. }());
  10404. BABYLON.PromisePolyfill = PromisePolyfill;
  10405. })(BABYLON || (BABYLON = {}));
  10406. //# sourceMappingURL=babylon.promise.js.map
  10407. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10408. var BABYLON;
  10409. (function (BABYLON) {
  10410. /**
  10411. * Helper class to push actions to a pool of workers.
  10412. */
  10413. var WorkerPool = /** @class */ (function () {
  10414. /**
  10415. * Constructor
  10416. * @param workers Array of workers to use for actions
  10417. */
  10418. function WorkerPool(workers) {
  10419. this._pendingActions = new Array();
  10420. this._workerInfos = workers.map(function (worker) { return ({
  10421. worker: worker,
  10422. active: false
  10423. }); });
  10424. }
  10425. /**
  10426. * Terminates all workers and clears any pending actions.
  10427. */
  10428. WorkerPool.prototype.dispose = function () {
  10429. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10430. var workerInfo = _a[_i];
  10431. workerInfo.worker.terminate();
  10432. }
  10433. delete this._workerInfos;
  10434. delete this._pendingActions;
  10435. };
  10436. /**
  10437. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10438. * pended until a worker has completed its action.
  10439. * @param action The action to perform. Call onComplete when the action is complete.
  10440. */
  10441. WorkerPool.prototype.push = function (action) {
  10442. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10443. var workerInfo = _a[_i];
  10444. if (!workerInfo.active) {
  10445. this._execute(workerInfo, action);
  10446. return;
  10447. }
  10448. }
  10449. this._pendingActions.push(action);
  10450. };
  10451. WorkerPool.prototype._execute = function (workerInfo, action) {
  10452. var _this = this;
  10453. workerInfo.active = true;
  10454. action(workerInfo.worker, function () {
  10455. workerInfo.active = false;
  10456. var nextAction = _this._pendingActions.shift();
  10457. if (nextAction) {
  10458. _this._execute(workerInfo, nextAction);
  10459. }
  10460. });
  10461. };
  10462. return WorkerPool;
  10463. }());
  10464. BABYLON.WorkerPool = WorkerPool;
  10465. })(BABYLON || (BABYLON = {}));
  10466. //# sourceMappingURL=babylon.workerPool.js.map
  10467. var BABYLON;
  10468. (function (BABYLON) {
  10469. /**
  10470. * @hidden
  10471. **/
  10472. var _AlphaState = /** @class */ (function () {
  10473. /**
  10474. * Initializes the state.
  10475. */
  10476. function _AlphaState() {
  10477. this._isAlphaBlendDirty = false;
  10478. this._isBlendFunctionParametersDirty = false;
  10479. this._isBlendEquationParametersDirty = false;
  10480. this._isBlendConstantsDirty = false;
  10481. this._alphaBlend = false;
  10482. this._blendFunctionParameters = new Array(4);
  10483. this._blendEquationParameters = new Array(2);
  10484. this._blendConstants = new Array(4);
  10485. this.reset();
  10486. }
  10487. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10488. get: function () {
  10489. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10490. },
  10491. enumerable: true,
  10492. configurable: true
  10493. });
  10494. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10495. get: function () {
  10496. return this._alphaBlend;
  10497. },
  10498. set: function (value) {
  10499. if (this._alphaBlend === value) {
  10500. return;
  10501. }
  10502. this._alphaBlend = value;
  10503. this._isAlphaBlendDirty = true;
  10504. },
  10505. enumerable: true,
  10506. configurable: true
  10507. });
  10508. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10509. if (this._blendConstants[0] === r &&
  10510. this._blendConstants[1] === g &&
  10511. this._blendConstants[2] === b &&
  10512. this._blendConstants[3] === a) {
  10513. return;
  10514. }
  10515. this._blendConstants[0] = r;
  10516. this._blendConstants[1] = g;
  10517. this._blendConstants[2] = b;
  10518. this._blendConstants[3] = a;
  10519. this._isBlendConstantsDirty = true;
  10520. };
  10521. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10522. if (this._blendFunctionParameters[0] === value0 &&
  10523. this._blendFunctionParameters[1] === value1 &&
  10524. this._blendFunctionParameters[2] === value2 &&
  10525. this._blendFunctionParameters[3] === value3) {
  10526. return;
  10527. }
  10528. this._blendFunctionParameters[0] = value0;
  10529. this._blendFunctionParameters[1] = value1;
  10530. this._blendFunctionParameters[2] = value2;
  10531. this._blendFunctionParameters[3] = value3;
  10532. this._isBlendFunctionParametersDirty = true;
  10533. };
  10534. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10535. if (this._blendEquationParameters[0] === rgb &&
  10536. this._blendEquationParameters[1] === alpha) {
  10537. return;
  10538. }
  10539. this._blendEquationParameters[0] = rgb;
  10540. this._blendEquationParameters[1] = alpha;
  10541. this._isBlendEquationParametersDirty = true;
  10542. };
  10543. _AlphaState.prototype.reset = function () {
  10544. this._alphaBlend = false;
  10545. this._blendFunctionParameters[0] = null;
  10546. this._blendFunctionParameters[1] = null;
  10547. this._blendFunctionParameters[2] = null;
  10548. this._blendFunctionParameters[3] = null;
  10549. this._blendEquationParameters[0] = null;
  10550. this._blendEquationParameters[1] = null;
  10551. this._blendConstants[0] = null;
  10552. this._blendConstants[1] = null;
  10553. this._blendConstants[2] = null;
  10554. this._blendConstants[3] = null;
  10555. this._isAlphaBlendDirty = true;
  10556. this._isBlendFunctionParametersDirty = false;
  10557. this._isBlendEquationParametersDirty = false;
  10558. this._isBlendConstantsDirty = false;
  10559. };
  10560. _AlphaState.prototype.apply = function (gl) {
  10561. if (!this.isDirty) {
  10562. return;
  10563. }
  10564. // Alpha blend
  10565. if (this._isAlphaBlendDirty) {
  10566. if (this._alphaBlend) {
  10567. gl.enable(gl.BLEND);
  10568. }
  10569. else {
  10570. gl.disable(gl.BLEND);
  10571. }
  10572. this._isAlphaBlendDirty = false;
  10573. }
  10574. // Alpha function
  10575. if (this._isBlendFunctionParametersDirty) {
  10576. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10577. this._isBlendFunctionParametersDirty = false;
  10578. }
  10579. // Alpha equation
  10580. if (this._isBlendEquationParametersDirty) {
  10581. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10582. this._isBlendEquationParametersDirty = false;
  10583. }
  10584. // Constants
  10585. if (this._isBlendConstantsDirty) {
  10586. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10587. this._isBlendConstantsDirty = false;
  10588. }
  10589. };
  10590. return _AlphaState;
  10591. }());
  10592. BABYLON._AlphaState = _AlphaState;
  10593. })(BABYLON || (BABYLON = {}));
  10594. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10595. var BABYLON;
  10596. (function (BABYLON) {
  10597. /**
  10598. * @hidden
  10599. **/
  10600. var _DepthCullingState = /** @class */ (function () {
  10601. /**
  10602. * Initializes the state.
  10603. */
  10604. function _DepthCullingState() {
  10605. this._isDepthTestDirty = false;
  10606. this._isDepthMaskDirty = false;
  10607. this._isDepthFuncDirty = false;
  10608. this._isCullFaceDirty = false;
  10609. this._isCullDirty = false;
  10610. this._isZOffsetDirty = false;
  10611. this._isFrontFaceDirty = false;
  10612. this.reset();
  10613. }
  10614. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10615. get: function () {
  10616. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10617. },
  10618. enumerable: true,
  10619. configurable: true
  10620. });
  10621. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10622. get: function () {
  10623. return this._zOffset;
  10624. },
  10625. set: function (value) {
  10626. if (this._zOffset === value) {
  10627. return;
  10628. }
  10629. this._zOffset = value;
  10630. this._isZOffsetDirty = true;
  10631. },
  10632. enumerable: true,
  10633. configurable: true
  10634. });
  10635. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10636. get: function () {
  10637. return this._cullFace;
  10638. },
  10639. set: function (value) {
  10640. if (this._cullFace === value) {
  10641. return;
  10642. }
  10643. this._cullFace = value;
  10644. this._isCullFaceDirty = true;
  10645. },
  10646. enumerable: true,
  10647. configurable: true
  10648. });
  10649. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10650. get: function () {
  10651. return this._cull;
  10652. },
  10653. set: function (value) {
  10654. if (this._cull === value) {
  10655. return;
  10656. }
  10657. this._cull = value;
  10658. this._isCullDirty = true;
  10659. },
  10660. enumerable: true,
  10661. configurable: true
  10662. });
  10663. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10664. get: function () {
  10665. return this._depthFunc;
  10666. },
  10667. set: function (value) {
  10668. if (this._depthFunc === value) {
  10669. return;
  10670. }
  10671. this._depthFunc = value;
  10672. this._isDepthFuncDirty = true;
  10673. },
  10674. enumerable: true,
  10675. configurable: true
  10676. });
  10677. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10678. get: function () {
  10679. return this._depthMask;
  10680. },
  10681. set: function (value) {
  10682. if (this._depthMask === value) {
  10683. return;
  10684. }
  10685. this._depthMask = value;
  10686. this._isDepthMaskDirty = true;
  10687. },
  10688. enumerable: true,
  10689. configurable: true
  10690. });
  10691. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10692. get: function () {
  10693. return this._depthTest;
  10694. },
  10695. set: function (value) {
  10696. if (this._depthTest === value) {
  10697. return;
  10698. }
  10699. this._depthTest = value;
  10700. this._isDepthTestDirty = true;
  10701. },
  10702. enumerable: true,
  10703. configurable: true
  10704. });
  10705. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10706. get: function () {
  10707. return this._frontFace;
  10708. },
  10709. set: function (value) {
  10710. if (this._frontFace === value) {
  10711. return;
  10712. }
  10713. this._frontFace = value;
  10714. this._isFrontFaceDirty = true;
  10715. },
  10716. enumerable: true,
  10717. configurable: true
  10718. });
  10719. _DepthCullingState.prototype.reset = function () {
  10720. this._depthMask = true;
  10721. this._depthTest = true;
  10722. this._depthFunc = null;
  10723. this._cullFace = null;
  10724. this._cull = null;
  10725. this._zOffset = 0;
  10726. this._frontFace = null;
  10727. this._isDepthTestDirty = true;
  10728. this._isDepthMaskDirty = true;
  10729. this._isDepthFuncDirty = false;
  10730. this._isCullFaceDirty = false;
  10731. this._isCullDirty = false;
  10732. this._isZOffsetDirty = false;
  10733. this._isFrontFaceDirty = false;
  10734. };
  10735. _DepthCullingState.prototype.apply = function (gl) {
  10736. if (!this.isDirty) {
  10737. return;
  10738. }
  10739. // Cull
  10740. if (this._isCullDirty) {
  10741. if (this.cull) {
  10742. gl.enable(gl.CULL_FACE);
  10743. }
  10744. else {
  10745. gl.disable(gl.CULL_FACE);
  10746. }
  10747. this._isCullDirty = false;
  10748. }
  10749. // Cull face
  10750. if (this._isCullFaceDirty) {
  10751. gl.cullFace(this.cullFace);
  10752. this._isCullFaceDirty = false;
  10753. }
  10754. // Depth mask
  10755. if (this._isDepthMaskDirty) {
  10756. gl.depthMask(this.depthMask);
  10757. this._isDepthMaskDirty = false;
  10758. }
  10759. // Depth test
  10760. if (this._isDepthTestDirty) {
  10761. if (this.depthTest) {
  10762. gl.enable(gl.DEPTH_TEST);
  10763. }
  10764. else {
  10765. gl.disable(gl.DEPTH_TEST);
  10766. }
  10767. this._isDepthTestDirty = false;
  10768. }
  10769. // Depth func
  10770. if (this._isDepthFuncDirty) {
  10771. gl.depthFunc(this.depthFunc);
  10772. this._isDepthFuncDirty = false;
  10773. }
  10774. // zOffset
  10775. if (this._isZOffsetDirty) {
  10776. if (this.zOffset) {
  10777. gl.enable(gl.POLYGON_OFFSET_FILL);
  10778. gl.polygonOffset(this.zOffset, 0);
  10779. }
  10780. else {
  10781. gl.disable(gl.POLYGON_OFFSET_FILL);
  10782. }
  10783. this._isZOffsetDirty = false;
  10784. }
  10785. // Front face
  10786. if (this._isFrontFaceDirty) {
  10787. gl.frontFace(this.frontFace);
  10788. this._isFrontFaceDirty = false;
  10789. }
  10790. };
  10791. return _DepthCullingState;
  10792. }());
  10793. BABYLON._DepthCullingState = _DepthCullingState;
  10794. })(BABYLON || (BABYLON = {}));
  10795. //# sourceMappingURL=babylon.depthCullingState.js.map
  10796. var BABYLON;
  10797. (function (BABYLON) {
  10798. /**
  10799. * @hidden
  10800. **/
  10801. var _StencilState = /** @class */ (function () {
  10802. function _StencilState() {
  10803. this._isStencilTestDirty = false;
  10804. this._isStencilMaskDirty = false;
  10805. this._isStencilFuncDirty = false;
  10806. this._isStencilOpDirty = false;
  10807. this.reset();
  10808. }
  10809. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10810. get: function () {
  10811. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10817. get: function () {
  10818. return this._stencilFunc;
  10819. },
  10820. set: function (value) {
  10821. if (this._stencilFunc === value) {
  10822. return;
  10823. }
  10824. this._stencilFunc = value;
  10825. this._isStencilFuncDirty = true;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10831. get: function () {
  10832. return this._stencilFuncRef;
  10833. },
  10834. set: function (value) {
  10835. if (this._stencilFuncRef === value) {
  10836. return;
  10837. }
  10838. this._stencilFuncRef = value;
  10839. this._isStencilFuncDirty = true;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10845. get: function () {
  10846. return this._stencilFuncMask;
  10847. },
  10848. set: function (value) {
  10849. if (this._stencilFuncMask === value) {
  10850. return;
  10851. }
  10852. this._stencilFuncMask = value;
  10853. this._isStencilFuncDirty = true;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10859. get: function () {
  10860. return this._stencilOpStencilFail;
  10861. },
  10862. set: function (value) {
  10863. if (this._stencilOpStencilFail === value) {
  10864. return;
  10865. }
  10866. this._stencilOpStencilFail = value;
  10867. this._isStencilOpDirty = true;
  10868. },
  10869. enumerable: true,
  10870. configurable: true
  10871. });
  10872. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10873. get: function () {
  10874. return this._stencilOpDepthFail;
  10875. },
  10876. set: function (value) {
  10877. if (this._stencilOpDepthFail === value) {
  10878. return;
  10879. }
  10880. this._stencilOpDepthFail = value;
  10881. this._isStencilOpDirty = true;
  10882. },
  10883. enumerable: true,
  10884. configurable: true
  10885. });
  10886. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10887. get: function () {
  10888. return this._stencilOpStencilDepthPass;
  10889. },
  10890. set: function (value) {
  10891. if (this._stencilOpStencilDepthPass === value) {
  10892. return;
  10893. }
  10894. this._stencilOpStencilDepthPass = value;
  10895. this._isStencilOpDirty = true;
  10896. },
  10897. enumerable: true,
  10898. configurable: true
  10899. });
  10900. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10901. get: function () {
  10902. return this._stencilMask;
  10903. },
  10904. set: function (value) {
  10905. if (this._stencilMask === value) {
  10906. return;
  10907. }
  10908. this._stencilMask = value;
  10909. this._isStencilMaskDirty = true;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10915. get: function () {
  10916. return this._stencilTest;
  10917. },
  10918. set: function (value) {
  10919. if (this._stencilTest === value) {
  10920. return;
  10921. }
  10922. this._stencilTest = value;
  10923. this._isStencilTestDirty = true;
  10924. },
  10925. enumerable: true,
  10926. configurable: true
  10927. });
  10928. _StencilState.prototype.reset = function () {
  10929. this._stencilTest = false;
  10930. this._stencilMask = 0xFF;
  10931. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10932. this._stencilFuncRef = 1;
  10933. this._stencilFuncMask = 0xFF;
  10934. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10935. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10936. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10937. this._isStencilTestDirty = true;
  10938. this._isStencilMaskDirty = true;
  10939. this._isStencilFuncDirty = true;
  10940. this._isStencilOpDirty = true;
  10941. };
  10942. _StencilState.prototype.apply = function (gl) {
  10943. if (!this.isDirty) {
  10944. return;
  10945. }
  10946. // Stencil test
  10947. if (this._isStencilTestDirty) {
  10948. if (this.stencilTest) {
  10949. gl.enable(gl.STENCIL_TEST);
  10950. }
  10951. else {
  10952. gl.disable(gl.STENCIL_TEST);
  10953. }
  10954. this._isStencilTestDirty = false;
  10955. }
  10956. // Stencil mask
  10957. if (this._isStencilMaskDirty) {
  10958. gl.stencilMask(this.stencilMask);
  10959. this._isStencilMaskDirty = false;
  10960. }
  10961. // Stencil func
  10962. if (this._isStencilFuncDirty) {
  10963. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10964. this._isStencilFuncDirty = false;
  10965. }
  10966. // Stencil op
  10967. if (this._isStencilOpDirty) {
  10968. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10969. this._isStencilOpDirty = false;
  10970. }
  10971. };
  10972. return _StencilState;
  10973. }());
  10974. BABYLON._StencilState = _StencilState;
  10975. })(BABYLON || (BABYLON = {}));
  10976. //# sourceMappingURL=babylon.stencilState.js.map
  10977. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10978. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10979. s = arguments[i];
  10980. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10981. t[p] = s[p];
  10982. }
  10983. return t;
  10984. };
  10985. var BABYLON;
  10986. (function (BABYLON) {
  10987. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10988. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10989. };
  10990. var compileRawShader = function (gl, source, type) {
  10991. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10992. gl.shaderSource(shader, source);
  10993. gl.compileShader(shader);
  10994. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10995. var log = gl.getShaderInfoLog(shader);
  10996. if (log) {
  10997. throw new Error(log);
  10998. }
  10999. }
  11000. if (!shader) {
  11001. throw new Error("Something went wrong while compile the shader.");
  11002. }
  11003. return shader;
  11004. };
  11005. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11006. var magFilter = gl.NEAREST;
  11007. var minFilter = gl.NEAREST;
  11008. switch (samplingMode) {
  11009. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11010. magFilter = gl.LINEAR;
  11011. if (generateMipMaps) {
  11012. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11013. }
  11014. else {
  11015. minFilter = gl.LINEAR;
  11016. }
  11017. break;
  11018. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11019. magFilter = gl.LINEAR;
  11020. if (generateMipMaps) {
  11021. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11022. }
  11023. else {
  11024. minFilter = gl.LINEAR;
  11025. }
  11026. break;
  11027. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11028. magFilter = gl.NEAREST;
  11029. if (generateMipMaps) {
  11030. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11031. }
  11032. else {
  11033. minFilter = gl.NEAREST;
  11034. }
  11035. break;
  11036. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11037. magFilter = gl.NEAREST;
  11038. if (generateMipMaps) {
  11039. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11040. }
  11041. else {
  11042. minFilter = gl.NEAREST;
  11043. }
  11044. break;
  11045. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11046. magFilter = gl.NEAREST;
  11047. if (generateMipMaps) {
  11048. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11049. }
  11050. else {
  11051. minFilter = gl.LINEAR;
  11052. }
  11053. break;
  11054. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11055. magFilter = gl.NEAREST;
  11056. if (generateMipMaps) {
  11057. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11058. }
  11059. else {
  11060. minFilter = gl.LINEAR;
  11061. }
  11062. break;
  11063. case BABYLON.Texture.NEAREST_LINEAR:
  11064. magFilter = gl.NEAREST;
  11065. minFilter = gl.LINEAR;
  11066. break;
  11067. case BABYLON.Texture.NEAREST_NEAREST:
  11068. magFilter = gl.NEAREST;
  11069. minFilter = gl.NEAREST;
  11070. break;
  11071. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11072. magFilter = gl.LINEAR;
  11073. if (generateMipMaps) {
  11074. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11075. }
  11076. else {
  11077. minFilter = gl.NEAREST;
  11078. }
  11079. break;
  11080. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11081. magFilter = gl.LINEAR;
  11082. if (generateMipMaps) {
  11083. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11084. }
  11085. else {
  11086. minFilter = gl.NEAREST;
  11087. }
  11088. break;
  11089. case BABYLON.Texture.LINEAR_LINEAR:
  11090. magFilter = gl.LINEAR;
  11091. minFilter = gl.LINEAR;
  11092. break;
  11093. case BABYLON.Texture.LINEAR_NEAREST:
  11094. magFilter = gl.LINEAR;
  11095. minFilter = gl.NEAREST;
  11096. break;
  11097. }
  11098. return {
  11099. min: minFilter,
  11100. mag: magFilter
  11101. };
  11102. };
  11103. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11104. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11105. var img;
  11106. var onload = function () {
  11107. loadedImages[index] = img;
  11108. loadedImages._internalCount++;
  11109. if (scene) {
  11110. scene._removePendingData(img);
  11111. }
  11112. if (loadedImages._internalCount === 6) {
  11113. onfinish(loadedImages);
  11114. }
  11115. };
  11116. var onerror = function (message, exception) {
  11117. if (scene) {
  11118. scene._removePendingData(img);
  11119. }
  11120. if (onErrorCallBack) {
  11121. onErrorCallBack(message, exception);
  11122. }
  11123. };
  11124. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11125. if (scene) {
  11126. scene._addPendingData(img);
  11127. }
  11128. };
  11129. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11130. if (onError === void 0) { onError = null; }
  11131. var loadedImages = [];
  11132. loadedImages._internalCount = 0;
  11133. for (var index = 0; index < 6; index++) {
  11134. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11135. }
  11136. };
  11137. var BufferPointer = /** @class */ (function () {
  11138. function BufferPointer() {
  11139. }
  11140. return BufferPointer;
  11141. }());
  11142. /**
  11143. * Interface for attribute information associated with buffer instanciation
  11144. */
  11145. var InstancingAttributeInfo = /** @class */ (function () {
  11146. function InstancingAttributeInfo() {
  11147. }
  11148. return InstancingAttributeInfo;
  11149. }());
  11150. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11151. /**
  11152. * Define options used to create a render target texture
  11153. */
  11154. var RenderTargetCreationOptions = /** @class */ (function () {
  11155. function RenderTargetCreationOptions() {
  11156. }
  11157. return RenderTargetCreationOptions;
  11158. }());
  11159. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11160. /**
  11161. * Define options used to create a depth texture
  11162. */
  11163. var DepthTextureCreationOptions = /** @class */ (function () {
  11164. function DepthTextureCreationOptions() {
  11165. }
  11166. return DepthTextureCreationOptions;
  11167. }());
  11168. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11169. /**
  11170. * Class used to describe the capabilities of the engine relatively to the current browser
  11171. */
  11172. var EngineCapabilities = /** @class */ (function () {
  11173. function EngineCapabilities() {
  11174. }
  11175. return EngineCapabilities;
  11176. }());
  11177. BABYLON.EngineCapabilities = EngineCapabilities;
  11178. /**
  11179. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11180. */
  11181. var Engine = /** @class */ (function () {
  11182. /**
  11183. * Creates a new engine
  11184. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11185. * @param antialias defines enable antialiasing (default: false)
  11186. * @param options defines further options to be sent to the getContext() function
  11187. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11188. */
  11189. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11190. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11191. var _this = this;
  11192. // Public members
  11193. /**
  11194. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11195. */
  11196. this.forcePOTTextures = false;
  11197. /**
  11198. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11199. */
  11200. this.isFullscreen = false;
  11201. /**
  11202. * Gets a boolean indicating if the pointer is currently locked
  11203. */
  11204. this.isPointerLock = false;
  11205. /**
  11206. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11207. */
  11208. this.cullBackFaces = true;
  11209. /**
  11210. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11211. */
  11212. this.renderEvenInBackground = true;
  11213. /**
  11214. * Gets or sets a boolean indicating that cache can be kept between frames
  11215. */
  11216. this.preventCacheWipeBetweenFrames = false;
  11217. /**
  11218. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11219. **/
  11220. this.enableOfflineSupport = false;
  11221. /**
  11222. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11223. **/
  11224. this.disableManifestCheck = false;
  11225. /**
  11226. * Gets the list of created scenes
  11227. */
  11228. this.scenes = new Array();
  11229. /**
  11230. * Gets the list of created postprocesses
  11231. */
  11232. this.postProcesses = new Array();
  11233. // Observables
  11234. /**
  11235. * Observable event triggered each time the rendering canvas is resized
  11236. */
  11237. this.onResizeObservable = new BABYLON.Observable();
  11238. /**
  11239. * Observable event triggered each time the canvas loses focus
  11240. */
  11241. this.onCanvasBlurObservable = new BABYLON.Observable();
  11242. /**
  11243. * Observable event triggered each time the canvas gains focus
  11244. */
  11245. this.onCanvasFocusObservable = new BABYLON.Observable();
  11246. /**
  11247. * Observable event triggered each time the canvas receives pointerout event
  11248. */
  11249. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11250. /**
  11251. * Observable event triggered before each texture is initialized
  11252. */
  11253. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11254. //WebVR
  11255. this._vrDisplay = undefined;
  11256. this._vrSupported = false;
  11257. this._vrExclusivePointerMode = false;
  11258. // Uniform buffers list
  11259. /**
  11260. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11261. */
  11262. this.disableUniformBuffers = false;
  11263. /** @hidden */
  11264. this._uniformBuffers = new Array();
  11265. // Observables
  11266. /**
  11267. * Observable raised when the engine begins a new frame
  11268. */
  11269. this.onBeginFrameObservable = new BABYLON.Observable();
  11270. /**
  11271. * Observable raised when the engine ends the current frame
  11272. */
  11273. this.onEndFrameObservable = new BABYLON.Observable();
  11274. /**
  11275. * Observable raised when the engine is about to compile a shader
  11276. */
  11277. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11278. /**
  11279. * Observable raised when the engine has jsut compiled a shader
  11280. */
  11281. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11282. this._windowIsBackground = false;
  11283. this._webGLVersion = 1.0;
  11284. /** @hidden */
  11285. this._badOS = false;
  11286. /** @hidden */
  11287. this._badDesktopOS = false;
  11288. /**
  11289. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11290. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11291. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11292. */
  11293. this.disableTextureBindingOptimization = false;
  11294. /**
  11295. * Observable signaled when VR display mode changes
  11296. */
  11297. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11298. /**
  11299. * Observable signaled when VR request present is complete
  11300. */
  11301. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11302. /**
  11303. * Observable signaled when VR request present starts
  11304. */
  11305. this.onVRRequestPresentStart = new BABYLON.Observable();
  11306. this._colorWrite = true;
  11307. /** @hidden */
  11308. this._drawCalls = new BABYLON.PerfCounter();
  11309. /** @hidden */
  11310. this._textureCollisions = new BABYLON.PerfCounter();
  11311. this._renderingQueueLaunched = false;
  11312. this._activeRenderLoops = new Array();
  11313. // Deterministic lockstepMaxSteps
  11314. this._deterministicLockstep = false;
  11315. this._lockstepMaxSteps = 4;
  11316. // Lost context
  11317. /**
  11318. * Observable signaled when a context lost event is raised
  11319. */
  11320. this.onContextLostObservable = new BABYLON.Observable();
  11321. /**
  11322. * Observable signaled when a context restored event is raised
  11323. */
  11324. this.onContextRestoredObservable = new BABYLON.Observable();
  11325. this._contextWasLost = false;
  11326. this._doNotHandleContextLost = false;
  11327. // FPS
  11328. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11329. this._fps = 60;
  11330. this._deltaTime = 0;
  11331. /**
  11332. * Turn this value on if you want to pause FPS computation when in background
  11333. */
  11334. this.disablePerformanceMonitorInBackground = false;
  11335. // States
  11336. /** @hidden */
  11337. this._depthCullingState = new BABYLON._DepthCullingState();
  11338. /** @hidden */
  11339. this._stencilState = new BABYLON._StencilState();
  11340. /** @hidden */
  11341. this._alphaState = new BABYLON._AlphaState();
  11342. /** @hidden */
  11343. this._alphaMode = Engine.ALPHA_DISABLE;
  11344. // Cache
  11345. this._internalTexturesCache = new Array();
  11346. /** @hidden */
  11347. this._activeChannel = 0;
  11348. this._currentTextureChannel = -1;
  11349. /** @hidden */
  11350. this._boundTexturesCache = {};
  11351. this._compiledEffects = {};
  11352. this._vertexAttribArraysEnabled = [];
  11353. this._uintIndicesCurrentlySet = false;
  11354. this._currentBoundBuffer = new Array();
  11355. this._currentBufferPointers = new Array();
  11356. this._currentInstanceLocations = new Array();
  11357. this._currentInstanceBuffers = new Array();
  11358. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11359. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11360. this._vaoRecordInProgress = false;
  11361. this._mustWipeVertexAttributes = false;
  11362. this._nextFreeTextureSlots = new Array();
  11363. this._maxSimultaneousTextures = 0;
  11364. this._activeRequests = new Array();
  11365. // Hardware supported Compressed Textures
  11366. this._texturesSupported = new Array();
  11367. this._onVRFullScreenTriggered = function () {
  11368. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11369. //get the old size before we change
  11370. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11371. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11372. //get the width and height, change the render size
  11373. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11374. _this.setHardwareScalingLevel(1);
  11375. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11376. }
  11377. else {
  11378. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11379. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11380. }
  11381. };
  11382. this._boundUniforms = {};
  11383. // Register promises
  11384. BABYLON.PromisePolyfill.Apply();
  11385. var canvas = null;
  11386. Engine.Instances.push(this);
  11387. if (!canvasOrContext) {
  11388. return;
  11389. }
  11390. options = options || {};
  11391. if (canvasOrContext.getContext) {
  11392. canvas = canvasOrContext;
  11393. this._renderingCanvas = canvas;
  11394. if (antialias != null) {
  11395. options.antialias = antialias;
  11396. }
  11397. if (options.deterministicLockstep === undefined) {
  11398. options.deterministicLockstep = false;
  11399. }
  11400. if (options.lockstepMaxSteps === undefined) {
  11401. options.lockstepMaxSteps = 4;
  11402. }
  11403. if (options.preserveDrawingBuffer === undefined) {
  11404. options.preserveDrawingBuffer = false;
  11405. }
  11406. if (options.audioEngine === undefined) {
  11407. options.audioEngine = true;
  11408. }
  11409. if (options.stencil === undefined) {
  11410. options.stencil = true;
  11411. }
  11412. this._deterministicLockstep = options.deterministicLockstep;
  11413. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11414. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11415. // Exceptions
  11416. if (navigator && navigator.userAgent) {
  11417. var ua = navigator.userAgent;
  11418. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11419. var exception = _a[_i];
  11420. var key = exception.key;
  11421. var targets = exception.targets;
  11422. if (ua.indexOf(key) > -1) {
  11423. if (exception.capture && exception.captureConstraint) {
  11424. var capture = exception.capture;
  11425. var constraint = exception.captureConstraint;
  11426. var regex = new RegExp(capture);
  11427. var matches = regex.exec(ua);
  11428. if (matches && matches.length > 0) {
  11429. var capturedValue = parseInt(matches[matches.length - 1]);
  11430. if (capturedValue >= constraint) {
  11431. continue;
  11432. }
  11433. }
  11434. }
  11435. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11436. var target = targets_1[_b];
  11437. switch (target) {
  11438. case "uniformBuffer":
  11439. this.disableUniformBuffers = true;
  11440. break;
  11441. case "textureBindingOptimization":
  11442. this.disableTextureBindingOptimization = true;
  11443. break;
  11444. }
  11445. }
  11446. }
  11447. }
  11448. }
  11449. // GL
  11450. if (!options.disableWebGL2Support) {
  11451. try {
  11452. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11453. if (this._gl) {
  11454. this._webGLVersion = 2.0;
  11455. }
  11456. }
  11457. catch (e) {
  11458. // Do nothing
  11459. }
  11460. }
  11461. if (!this._gl) {
  11462. if (!canvas) {
  11463. throw new Error("The provided canvas is null or undefined.");
  11464. }
  11465. try {
  11466. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11467. }
  11468. catch (e) {
  11469. throw new Error("WebGL not supported");
  11470. }
  11471. }
  11472. if (!this._gl) {
  11473. throw new Error("WebGL not supported");
  11474. }
  11475. this._onCanvasFocus = function () {
  11476. _this.onCanvasFocusObservable.notifyObservers(_this);
  11477. };
  11478. this._onCanvasBlur = function () {
  11479. _this.onCanvasBlurObservable.notifyObservers(_this);
  11480. };
  11481. canvas.addEventListener("focus", this._onCanvasFocus);
  11482. canvas.addEventListener("blur", this._onCanvasBlur);
  11483. this._onBlur = function () {
  11484. if (_this.disablePerformanceMonitorInBackground) {
  11485. _this._performanceMonitor.disable();
  11486. }
  11487. _this._windowIsBackground = true;
  11488. };
  11489. this._onFocus = function () {
  11490. if (_this.disablePerformanceMonitorInBackground) {
  11491. _this._performanceMonitor.enable();
  11492. }
  11493. _this._windowIsBackground = false;
  11494. };
  11495. this._onCanvasPointerOut = function (ev) {
  11496. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11497. };
  11498. window.addEventListener("blur", this._onBlur);
  11499. window.addEventListener("focus", this._onFocus);
  11500. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11501. // Context lost
  11502. if (!this._doNotHandleContextLost) {
  11503. this._onContextLost = function (evt) {
  11504. evt.preventDefault();
  11505. _this._contextWasLost = true;
  11506. BABYLON.Tools.Warn("WebGL context lost.");
  11507. _this.onContextLostObservable.notifyObservers(_this);
  11508. };
  11509. this._onContextRestored = function (evt) {
  11510. // Adding a timeout to avoid race condition at browser level
  11511. setTimeout(function () {
  11512. // Rebuild gl context
  11513. _this._initGLContext();
  11514. // Rebuild effects
  11515. _this._rebuildEffects();
  11516. // Rebuild textures
  11517. _this._rebuildInternalTextures();
  11518. // Rebuild buffers
  11519. _this._rebuildBuffers();
  11520. // Cache
  11521. _this.wipeCaches(true);
  11522. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11523. _this.onContextRestoredObservable.notifyObservers(_this);
  11524. _this._contextWasLost = false;
  11525. }, 0);
  11526. };
  11527. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11528. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11529. }
  11530. }
  11531. else {
  11532. this._gl = canvasOrContext;
  11533. this._renderingCanvas = this._gl.canvas;
  11534. if (this._gl.renderbufferStorageMultisample) {
  11535. this._webGLVersion = 2.0;
  11536. }
  11537. options.stencil = this._gl.getContextAttributes().stencil;
  11538. }
  11539. // Viewport
  11540. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11541. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11542. this.resize();
  11543. this._isStencilEnable = options.stencil ? true : false;
  11544. this._initGLContext();
  11545. if (canvas) {
  11546. // Fullscreen
  11547. this._onFullscreenChange = function () {
  11548. if (document.fullscreen !== undefined) {
  11549. _this.isFullscreen = document.fullscreen;
  11550. }
  11551. else if (document.mozFullScreen !== undefined) {
  11552. _this.isFullscreen = document.mozFullScreen;
  11553. }
  11554. else if (document.webkitIsFullScreen !== undefined) {
  11555. _this.isFullscreen = document.webkitIsFullScreen;
  11556. }
  11557. else if (document.msIsFullScreen !== undefined) {
  11558. _this.isFullscreen = document.msIsFullScreen;
  11559. }
  11560. // Pointer lock
  11561. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11562. canvas.requestPointerLock = canvas.requestPointerLock ||
  11563. canvas.msRequestPointerLock ||
  11564. canvas.mozRequestPointerLock ||
  11565. canvas.webkitRequestPointerLock;
  11566. if (canvas.requestPointerLock) {
  11567. canvas.requestPointerLock();
  11568. }
  11569. }
  11570. };
  11571. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11572. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11573. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11574. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11575. // Pointer lock
  11576. this._onPointerLockChange = function () {
  11577. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11578. document.webkitPointerLockElement === canvas ||
  11579. document.msPointerLockElement === canvas ||
  11580. document.pointerLockElement === canvas);
  11581. };
  11582. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11583. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11584. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11585. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11586. this._onVRDisplayPointerRestricted = function () {
  11587. if (canvas) {
  11588. canvas.requestPointerLock();
  11589. }
  11590. };
  11591. this._onVRDisplayPointerUnrestricted = function () {
  11592. document.exitPointerLock();
  11593. };
  11594. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11595. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11596. }
  11597. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11598. Engine.audioEngine = new BABYLON.AudioEngine();
  11599. }
  11600. // Prepare buffer pointers
  11601. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11602. this._currentBufferPointers[i] = new BufferPointer();
  11603. }
  11604. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11605. // Load WebVR Devices
  11606. if (options.autoEnableWebVR) {
  11607. this.initWebVR();
  11608. }
  11609. // Detect if we are running on a faulty buggy OS.
  11610. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11611. // Detect if we are running on a faulty buggy desktop OS.
  11612. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11613. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11614. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11615. }
  11616. Object.defineProperty(Engine, "LastCreatedEngine", {
  11617. /**
  11618. * Gets the latest created engine
  11619. */
  11620. get: function () {
  11621. if (Engine.Instances.length === 0) {
  11622. return null;
  11623. }
  11624. return Engine.Instances[Engine.Instances.length - 1];
  11625. },
  11626. enumerable: true,
  11627. configurable: true
  11628. });
  11629. Object.defineProperty(Engine, "LastCreatedScene", {
  11630. /**
  11631. * Gets the latest created scene
  11632. */
  11633. get: function () {
  11634. var lastCreatedEngine = Engine.LastCreatedEngine;
  11635. if (!lastCreatedEngine) {
  11636. return null;
  11637. }
  11638. if (lastCreatedEngine.scenes.length === 0) {
  11639. return null;
  11640. }
  11641. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11642. },
  11643. enumerable: true,
  11644. configurable: true
  11645. });
  11646. /**
  11647. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11648. * @param flag defines which part of the materials must be marked as dirty
  11649. * @param predicate defines a predicate used to filter which materials should be affected
  11650. */
  11651. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11652. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11653. var engine = Engine.Instances[engineIndex];
  11654. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11655. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11656. }
  11657. }
  11658. };
  11659. Object.defineProperty(Engine, "NEVER", {
  11660. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11661. get: function () {
  11662. return Engine._NEVER;
  11663. },
  11664. enumerable: true,
  11665. configurable: true
  11666. });
  11667. Object.defineProperty(Engine, "ALWAYS", {
  11668. /** 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 */
  11669. get: function () {
  11670. return Engine._ALWAYS;
  11671. },
  11672. enumerable: true,
  11673. configurable: true
  11674. });
  11675. Object.defineProperty(Engine, "LESS", {
  11676. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11677. get: function () {
  11678. return Engine._LESS;
  11679. },
  11680. enumerable: true,
  11681. configurable: true
  11682. });
  11683. Object.defineProperty(Engine, "EQUAL", {
  11684. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11685. get: function () {
  11686. return Engine._EQUAL;
  11687. },
  11688. enumerable: true,
  11689. configurable: true
  11690. });
  11691. Object.defineProperty(Engine, "LEQUAL", {
  11692. /** 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 */
  11693. get: function () {
  11694. return Engine._LEQUAL;
  11695. },
  11696. enumerable: true,
  11697. configurable: true
  11698. });
  11699. Object.defineProperty(Engine, "GREATER", {
  11700. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11701. get: function () {
  11702. return Engine._GREATER;
  11703. },
  11704. enumerable: true,
  11705. configurable: true
  11706. });
  11707. Object.defineProperty(Engine, "GEQUAL", {
  11708. /** 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 */
  11709. get: function () {
  11710. return Engine._GEQUAL;
  11711. },
  11712. enumerable: true,
  11713. configurable: true
  11714. });
  11715. Object.defineProperty(Engine, "NOTEQUAL", {
  11716. /** 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 */
  11717. get: function () {
  11718. return Engine._NOTEQUAL;
  11719. },
  11720. enumerable: true,
  11721. configurable: true
  11722. });
  11723. Object.defineProperty(Engine, "KEEP", {
  11724. /** Passed to stencilOperation to specify that stencil value must be kept */
  11725. get: function () {
  11726. return Engine._KEEP;
  11727. },
  11728. enumerable: true,
  11729. configurable: true
  11730. });
  11731. Object.defineProperty(Engine, "REPLACE", {
  11732. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11733. get: function () {
  11734. return Engine._REPLACE;
  11735. },
  11736. enumerable: true,
  11737. configurable: true
  11738. });
  11739. Object.defineProperty(Engine, "INCR", {
  11740. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11741. get: function () {
  11742. return Engine._INCR;
  11743. },
  11744. enumerable: true,
  11745. configurable: true
  11746. });
  11747. Object.defineProperty(Engine, "DECR", {
  11748. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11749. get: function () {
  11750. return Engine._DECR;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Object.defineProperty(Engine, "INVERT", {
  11756. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11757. get: function () {
  11758. return Engine._INVERT;
  11759. },
  11760. enumerable: true,
  11761. configurable: true
  11762. });
  11763. Object.defineProperty(Engine, "INCR_WRAP", {
  11764. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11765. get: function () {
  11766. return Engine._INCR_WRAP;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(Engine, "DECR_WRAP", {
  11772. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11773. get: function () {
  11774. return Engine._DECR_WRAP;
  11775. },
  11776. enumerable: true,
  11777. configurable: true
  11778. });
  11779. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11780. // Alpha
  11781. /** Defines that alpha blending is disabled */
  11782. get: function () {
  11783. return Engine._ALPHA_DISABLE;
  11784. },
  11785. enumerable: true,
  11786. configurable: true
  11787. });
  11788. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11789. /** Defines that alpha blending to SRC + DEST */
  11790. get: function () {
  11791. return Engine._ALPHA_ONEONE;
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. Object.defineProperty(Engine, "ALPHA_ADD", {
  11797. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11798. get: function () {
  11799. return Engine._ALPHA_ADD;
  11800. },
  11801. enumerable: true,
  11802. configurable: true
  11803. });
  11804. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11805. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11806. get: function () {
  11807. return Engine._ALPHA_COMBINE;
  11808. },
  11809. enumerable: true,
  11810. configurable: true
  11811. });
  11812. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11813. /** Defines that alpha blending to DEST - SRC * DEST */
  11814. get: function () {
  11815. return Engine._ALPHA_SUBTRACT;
  11816. },
  11817. enumerable: true,
  11818. configurable: true
  11819. });
  11820. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11821. /** Defines that alpha blending to SRC * DEST */
  11822. get: function () {
  11823. return Engine._ALPHA_MULTIPLY;
  11824. },
  11825. enumerable: true,
  11826. configurable: true
  11827. });
  11828. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11829. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11830. get: function () {
  11831. return Engine._ALPHA_MAXIMIZED;
  11832. },
  11833. enumerable: true,
  11834. configurable: true
  11835. });
  11836. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11837. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11838. get: function () {
  11839. return Engine._ALPHA_PREMULTIPLIED;
  11840. },
  11841. enumerable: true,
  11842. configurable: true
  11843. });
  11844. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11845. /**
  11846. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11847. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11848. */
  11849. get: function () {
  11850. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11856. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11857. get: function () {
  11858. return Engine._ALPHA_INTERPOLATE;
  11859. },
  11860. enumerable: true,
  11861. configurable: true
  11862. });
  11863. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11864. /**
  11865. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11866. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11867. */
  11868. get: function () {
  11869. return Engine._ALPHA_SCREENMODE;
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11875. // Delays
  11876. /** Defines that the ressource is not delayed*/
  11877. get: function () {
  11878. return Engine._DELAYLOADSTATE_NONE;
  11879. },
  11880. enumerable: true,
  11881. configurable: true
  11882. });
  11883. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11884. /** Defines that the ressource was successfully delay loaded */
  11885. get: function () {
  11886. return Engine._DELAYLOADSTATE_LOADED;
  11887. },
  11888. enumerable: true,
  11889. configurable: true
  11890. });
  11891. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11892. /** Defines that the ressource is currently delay loading */
  11893. get: function () {
  11894. return Engine._DELAYLOADSTATE_LOADING;
  11895. },
  11896. enumerable: true,
  11897. configurable: true
  11898. });
  11899. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11900. /** Defines that the ressource is delayed and has not started loading */
  11901. get: function () {
  11902. return Engine._DELAYLOADSTATE_NOTLOADED;
  11903. },
  11904. enumerable: true,
  11905. configurable: true
  11906. });
  11907. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11908. /** ALPHA */
  11909. get: function () {
  11910. return Engine._TEXTUREFORMAT_ALPHA;
  11911. },
  11912. enumerable: true,
  11913. configurable: true
  11914. });
  11915. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11916. /** LUMINANCE */
  11917. get: function () {
  11918. return Engine._TEXTUREFORMAT_LUMINANCE;
  11919. },
  11920. enumerable: true,
  11921. configurable: true
  11922. });
  11923. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11924. /**
  11925. * R32F
  11926. */
  11927. get: function () {
  11928. return Engine._TEXTUREFORMAT_R32F;
  11929. },
  11930. enumerable: true,
  11931. configurable: true
  11932. });
  11933. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11934. /**
  11935. * RG32F
  11936. */
  11937. get: function () {
  11938. return Engine._TEXTUREFORMAT_RG32F;
  11939. },
  11940. enumerable: true,
  11941. configurable: true
  11942. });
  11943. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11944. /**
  11945. * RGB32F
  11946. */
  11947. get: function () {
  11948. return Engine._TEXTUREFORMAT_RGB32F;
  11949. },
  11950. enumerable: true,
  11951. configurable: true
  11952. });
  11953. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11954. /**
  11955. * RGBA32F
  11956. */
  11957. get: function () {
  11958. return Engine._TEXTUREFORMAT_RGBA32F;
  11959. },
  11960. enumerable: true,
  11961. configurable: true
  11962. });
  11963. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11964. /** LUMINANCE_ALPHA */
  11965. get: function () {
  11966. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11967. },
  11968. enumerable: true,
  11969. configurable: true
  11970. });
  11971. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11972. /** RGB */
  11973. get: function () {
  11974. return Engine._TEXTUREFORMAT_RGB;
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11980. /** RGBA */
  11981. get: function () {
  11982. return Engine._TEXTUREFORMAT_RGBA;
  11983. },
  11984. enumerable: true,
  11985. configurable: true
  11986. });
  11987. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11988. /** UNSIGNED_INT */
  11989. get: function () {
  11990. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11991. },
  11992. enumerable: true,
  11993. configurable: true
  11994. });
  11995. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11996. /** FLOAT */
  11997. get: function () {
  11998. return Engine._TEXTURETYPE_FLOAT;
  11999. },
  12000. enumerable: true,
  12001. configurable: true
  12002. });
  12003. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12004. /** HALF_FLOAT */
  12005. get: function () {
  12006. return Engine._TEXTURETYPE_HALF_FLOAT;
  12007. },
  12008. enumerable: true,
  12009. configurable: true
  12010. });
  12011. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12012. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12013. get: function () {
  12014. return Engine._SCALEMODE_FLOOR;
  12015. },
  12016. enumerable: true,
  12017. configurable: true
  12018. });
  12019. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12020. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12021. get: function () {
  12022. return Engine._SCALEMODE_NEAREST;
  12023. },
  12024. enumerable: true,
  12025. configurable: true
  12026. });
  12027. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12028. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12029. get: function () {
  12030. return Engine._SCALEMODE_CEILING;
  12031. },
  12032. enumerable: true,
  12033. configurable: true
  12034. });
  12035. Object.defineProperty(Engine, "Version", {
  12036. /**
  12037. * Returns the current version of the framework
  12038. */
  12039. get: function () {
  12040. return "3.3.0-alpha.2";
  12041. },
  12042. enumerable: true,
  12043. configurable: true
  12044. });
  12045. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12046. /**
  12047. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12048. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12049. */
  12050. get: function () {
  12051. return this._vrExclusivePointerMode;
  12052. },
  12053. enumerable: true,
  12054. configurable: true
  12055. });
  12056. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12057. /**
  12058. * Gets a boolean indicating that the engine supports uniform buffers
  12059. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12060. */
  12061. get: function () {
  12062. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12063. },
  12064. enumerable: true,
  12065. configurable: true
  12066. });
  12067. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12068. /**
  12069. * Gets a boolean indicating that only power of 2 textures are supported
  12070. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12071. */
  12072. get: function () {
  12073. return this._webGLVersion < 2 || this.forcePOTTextures;
  12074. },
  12075. enumerable: true,
  12076. configurable: true
  12077. });
  12078. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12079. /**
  12080. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12081. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12082. */
  12083. get: function () {
  12084. return this._doNotHandleContextLost;
  12085. },
  12086. set: function (value) {
  12087. this._doNotHandleContextLost = value;
  12088. },
  12089. enumerable: true,
  12090. configurable: true
  12091. });
  12092. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12093. /**
  12094. * Gets the performance monitor attached to this engine
  12095. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12096. */
  12097. get: function () {
  12098. return this._performanceMonitor;
  12099. },
  12100. enumerable: true,
  12101. configurable: true
  12102. });
  12103. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12104. /**
  12105. * Gets the list of texture formats supported
  12106. */
  12107. get: function () {
  12108. return this._texturesSupported;
  12109. },
  12110. enumerable: true,
  12111. configurable: true
  12112. });
  12113. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12114. /**
  12115. * Gets the list of texture formats in use
  12116. */
  12117. get: function () {
  12118. return this._textureFormatInUse;
  12119. },
  12120. enumerable: true,
  12121. configurable: true
  12122. });
  12123. Object.defineProperty(Engine.prototype, "currentViewport", {
  12124. /**
  12125. * Gets the current viewport
  12126. */
  12127. get: function () {
  12128. return this._cachedViewport;
  12129. },
  12130. enumerable: true,
  12131. configurable: true
  12132. });
  12133. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12134. /**
  12135. * Gets the default empty texture
  12136. */
  12137. get: function () {
  12138. if (!this._emptyTexture) {
  12139. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12140. }
  12141. return this._emptyTexture;
  12142. },
  12143. enumerable: true,
  12144. configurable: true
  12145. });
  12146. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12147. /**
  12148. * Gets the default empty 3D texture
  12149. */
  12150. get: function () {
  12151. if (!this._emptyTexture3D) {
  12152. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12153. }
  12154. return this._emptyTexture3D;
  12155. },
  12156. enumerable: true,
  12157. configurable: true
  12158. });
  12159. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12160. /**
  12161. * Gets the default empty cube texture
  12162. */
  12163. get: function () {
  12164. if (!this._emptyCubeTexture) {
  12165. var faceData = new Uint8Array(4);
  12166. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12167. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12168. }
  12169. return this._emptyCubeTexture;
  12170. },
  12171. enumerable: true,
  12172. configurable: true
  12173. });
  12174. Engine.prototype._rebuildInternalTextures = function () {
  12175. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12176. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12177. var internalTexture = currentState_1[_i];
  12178. internalTexture._rebuild();
  12179. }
  12180. };
  12181. Engine.prototype._rebuildEffects = function () {
  12182. for (var key in this._compiledEffects) {
  12183. var effect = this._compiledEffects[key];
  12184. effect._prepareEffect();
  12185. }
  12186. BABYLON.Effect.ResetCache();
  12187. };
  12188. Engine.prototype._rebuildBuffers = function () {
  12189. // Index / Vertex
  12190. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12191. var scene = _a[_i];
  12192. scene.resetCachedMaterial();
  12193. scene._rebuildGeometries();
  12194. scene._rebuildTextures();
  12195. }
  12196. // Uniforms
  12197. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12198. var uniformBuffer = _c[_b];
  12199. uniformBuffer._rebuild();
  12200. }
  12201. };
  12202. Engine.prototype._initGLContext = function () {
  12203. // Caps
  12204. this._caps = new EngineCapabilities();
  12205. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12206. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12207. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12208. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12209. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12210. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12211. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12212. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12213. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12214. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12215. // Infos
  12216. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12217. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12218. if (rendererInfo != null) {
  12219. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12220. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12221. }
  12222. if (!this._glVendor) {
  12223. this._glVendor = "Unknown vendor";
  12224. }
  12225. if (!this._glRenderer) {
  12226. this._glRenderer = "Unknown renderer";
  12227. }
  12228. // Constants
  12229. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12230. if (this._gl.RGBA16F !== 0x881A) {
  12231. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12232. }
  12233. if (this._gl.RGBA32F !== 0x8814) {
  12234. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12235. }
  12236. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12237. this._gl.DEPTH24_STENCIL8 = 35056;
  12238. }
  12239. // Extensions
  12240. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12241. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12242. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12243. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12244. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12245. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12246. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12247. 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');
  12248. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12249. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12250. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12251. this._caps.highPrecisionShaderSupported = true;
  12252. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12253. if (this._caps.timerQuery) {
  12254. if (this._webGLVersion === 1) {
  12255. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12256. }
  12257. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12258. }
  12259. // Checks if some of the format renders first to allow the use of webgl inspector.
  12260. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12261. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12262. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12263. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12264. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12265. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12266. if (this._webGLVersion > 1) {
  12267. this._gl.HALF_FLOAT_OES = 0x140B;
  12268. }
  12269. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12270. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12271. // Draw buffers
  12272. if (this._webGLVersion > 1) {
  12273. this._caps.drawBuffersExtension = true;
  12274. }
  12275. else {
  12276. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12277. if (drawBuffersExtension !== null) {
  12278. this._caps.drawBuffersExtension = true;
  12279. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12280. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12281. for (var i = 0; i < 16; i++) {
  12282. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12283. }
  12284. }
  12285. else {
  12286. this._caps.drawBuffersExtension = false;
  12287. }
  12288. }
  12289. // Depth Texture
  12290. if (this._webGLVersion > 1) {
  12291. this._caps.depthTextureExtension = true;
  12292. }
  12293. else {
  12294. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12295. if (depthTextureExtension != null) {
  12296. this._caps.depthTextureExtension = true;
  12297. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12298. }
  12299. }
  12300. // Vertex array object
  12301. if (this._webGLVersion > 1) {
  12302. this._caps.vertexArrayObject = true;
  12303. }
  12304. else {
  12305. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12306. if (vertexArrayObjectExtension != null) {
  12307. this._caps.vertexArrayObject = true;
  12308. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12309. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12310. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12311. }
  12312. else {
  12313. this._caps.vertexArrayObject = false;
  12314. }
  12315. }
  12316. // Instances count
  12317. if (this._webGLVersion > 1) {
  12318. this._caps.instancedArrays = true;
  12319. }
  12320. else {
  12321. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12322. if (instanceExtension != null) {
  12323. this._caps.instancedArrays = true;
  12324. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12325. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12326. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12327. }
  12328. else {
  12329. this._caps.instancedArrays = false;
  12330. }
  12331. }
  12332. // Intelligently add supported compressed formats in order to check for.
  12333. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12334. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12335. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12336. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12337. if (this._caps.astc)
  12338. this.texturesSupported.push('-astc.ktx');
  12339. if (this._caps.s3tc)
  12340. this.texturesSupported.push('-dxt.ktx');
  12341. if (this._caps.pvrtc)
  12342. this.texturesSupported.push('-pvrtc.ktx');
  12343. if (this._caps.etc2)
  12344. this.texturesSupported.push('-etc2.ktx');
  12345. if (this._caps.etc1)
  12346. this.texturesSupported.push('-etc1.ktx');
  12347. if (this._gl.getShaderPrecisionFormat) {
  12348. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12349. if (highp) {
  12350. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12351. }
  12352. }
  12353. // Depth buffer
  12354. this.setDepthBuffer(true);
  12355. this.setDepthFunctionToLessOrEqual();
  12356. this.setDepthWrite(true);
  12357. // Texture maps
  12358. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12359. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12360. this._nextFreeTextureSlots.push(slot);
  12361. }
  12362. };
  12363. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12364. /**
  12365. * Gets version of the current webGL context
  12366. */
  12367. get: function () {
  12368. return this._webGLVersion;
  12369. },
  12370. enumerable: true,
  12371. configurable: true
  12372. });
  12373. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12374. /**
  12375. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12376. */
  12377. get: function () {
  12378. return this._isStencilEnable;
  12379. },
  12380. enumerable: true,
  12381. configurable: true
  12382. });
  12383. Engine.prototype._prepareWorkingCanvas = function () {
  12384. if (this._workingCanvas) {
  12385. return;
  12386. }
  12387. this._workingCanvas = document.createElement("canvas");
  12388. var context = this._workingCanvas.getContext("2d");
  12389. if (context) {
  12390. this._workingContext = context;
  12391. }
  12392. };
  12393. /**
  12394. * Reset the texture cache to empty state
  12395. */
  12396. Engine.prototype.resetTextureCache = function () {
  12397. for (var key in this._boundTexturesCache) {
  12398. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12399. continue;
  12400. }
  12401. var boundTexture = this._boundTexturesCache[key];
  12402. if (boundTexture) {
  12403. this._removeDesignatedSlot(boundTexture);
  12404. }
  12405. this._boundTexturesCache[key] = null;
  12406. }
  12407. if (!this.disableTextureBindingOptimization) {
  12408. this._nextFreeTextureSlots = [];
  12409. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12410. this._nextFreeTextureSlots.push(slot);
  12411. }
  12412. }
  12413. this._currentTextureChannel = -1;
  12414. };
  12415. /**
  12416. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12417. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12418. * @returns true if engine is in deterministic lock step mode
  12419. */
  12420. Engine.prototype.isDeterministicLockStep = function () {
  12421. return this._deterministicLockstep;
  12422. };
  12423. /**
  12424. * Gets the max steps when engine is running in deterministic lock step
  12425. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12426. * @returns the max steps
  12427. */
  12428. Engine.prototype.getLockstepMaxSteps = function () {
  12429. return this._lockstepMaxSteps;
  12430. };
  12431. /**
  12432. * Gets an object containing information about the current webGL context
  12433. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12434. */
  12435. Engine.prototype.getGlInfo = function () {
  12436. return {
  12437. vendor: this._glVendor,
  12438. renderer: this._glRenderer,
  12439. version: this._glVersion
  12440. };
  12441. };
  12442. /**
  12443. * Gets current aspect ratio
  12444. * @param camera defines the camera to use to get the aspect ratio
  12445. * @param useScreen defines if screen size must be used (or the current render target if any)
  12446. * @returns a number defining the aspect ratio
  12447. */
  12448. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12449. if (useScreen === void 0) { useScreen = false; }
  12450. var viewport = camera.viewport;
  12451. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12452. };
  12453. /**
  12454. * Gets current screen aspect ratio
  12455. * @returns a number defining the aspect ratio
  12456. */
  12457. Engine.prototype.getScreenAspectRatio = function () {
  12458. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12459. };
  12460. /**
  12461. * Gets the current render width
  12462. * @param useScreen defines if screen size must be used (or the current render target if any)
  12463. * @returns a number defining the current render width
  12464. */
  12465. Engine.prototype.getRenderWidth = function (useScreen) {
  12466. if (useScreen === void 0) { useScreen = false; }
  12467. if (!useScreen && this._currentRenderTarget) {
  12468. return this._currentRenderTarget.width;
  12469. }
  12470. return this._gl.drawingBufferWidth;
  12471. };
  12472. /**
  12473. * Gets the current render height
  12474. * @param useScreen defines if screen size must be used (or the current render target if any)
  12475. * @returns a number defining the current render height
  12476. */
  12477. Engine.prototype.getRenderHeight = function (useScreen) {
  12478. if (useScreen === void 0) { useScreen = false; }
  12479. if (!useScreen && this._currentRenderTarget) {
  12480. return this._currentRenderTarget.height;
  12481. }
  12482. return this._gl.drawingBufferHeight;
  12483. };
  12484. /**
  12485. * Gets the HTML canvas attached with the current webGL context
  12486. * @returns a HTML canvas
  12487. */
  12488. Engine.prototype.getRenderingCanvas = function () {
  12489. return this._renderingCanvas;
  12490. };
  12491. /**
  12492. * Gets the client rect of the HTML canvas attached with the current webGL context
  12493. * @returns a client rectanglee
  12494. */
  12495. Engine.prototype.getRenderingCanvasClientRect = function () {
  12496. if (!this._renderingCanvas) {
  12497. return null;
  12498. }
  12499. return this._renderingCanvas.getBoundingClientRect();
  12500. };
  12501. /**
  12502. * Defines the hardware scaling level.
  12503. * By default the hardware scaling level is computed from the window device ratio.
  12504. * 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.
  12505. * @param level defines the level to use
  12506. */
  12507. Engine.prototype.setHardwareScalingLevel = function (level) {
  12508. this._hardwareScalingLevel = level;
  12509. this.resize();
  12510. };
  12511. /**
  12512. * Gets the current hardware scaling level.
  12513. * By default the hardware scaling level is computed from the window device ratio.
  12514. * 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.
  12515. * @returns a number indicating the current hardware scaling level
  12516. */
  12517. Engine.prototype.getHardwareScalingLevel = function () {
  12518. return this._hardwareScalingLevel;
  12519. };
  12520. /**
  12521. * Gets the list of loaded textures
  12522. * @returns an array containing all loaded textures
  12523. */
  12524. Engine.prototype.getLoadedTexturesCache = function () {
  12525. return this._internalTexturesCache;
  12526. };
  12527. /**
  12528. * Gets the object containing all engine capabilities
  12529. * @returns the EngineCapabilities object
  12530. */
  12531. Engine.prototype.getCaps = function () {
  12532. return this._caps;
  12533. };
  12534. Object.defineProperty(Engine.prototype, "drawCalls", {
  12535. /** @hidden */
  12536. get: function () {
  12537. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12538. return 0;
  12539. },
  12540. enumerable: true,
  12541. configurable: true
  12542. });
  12543. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12544. /** @hidden */
  12545. get: function () {
  12546. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12547. return null;
  12548. },
  12549. enumerable: true,
  12550. configurable: true
  12551. });
  12552. /**
  12553. * Gets the current depth function
  12554. * @returns a number defining the depth function
  12555. */
  12556. Engine.prototype.getDepthFunction = function () {
  12557. return this._depthCullingState.depthFunc;
  12558. };
  12559. /**
  12560. * Sets the current depth function
  12561. * @param depthFunc defines the function to use
  12562. */
  12563. Engine.prototype.setDepthFunction = function (depthFunc) {
  12564. this._depthCullingState.depthFunc = depthFunc;
  12565. };
  12566. /**
  12567. * Sets the current depth function to GREATER
  12568. */
  12569. Engine.prototype.setDepthFunctionToGreater = function () {
  12570. this._depthCullingState.depthFunc = this._gl.GREATER;
  12571. };
  12572. /**
  12573. * Sets the current depth function to GEQUAL
  12574. */
  12575. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12576. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12577. };
  12578. /**
  12579. * Sets the current depth function to LESS
  12580. */
  12581. Engine.prototype.setDepthFunctionToLess = function () {
  12582. this._depthCullingState.depthFunc = this._gl.LESS;
  12583. };
  12584. /**
  12585. * Sets the current depth function to LEQUAL
  12586. */
  12587. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12588. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12589. };
  12590. /**
  12591. * Gets a boolean indicating if stencil buffer is enabled
  12592. * @returns the current stencil buffer state
  12593. */
  12594. Engine.prototype.getStencilBuffer = function () {
  12595. return this._stencilState.stencilTest;
  12596. };
  12597. /**
  12598. * Enable or disable the stencil buffer
  12599. * @param enable defines if the stencil buffer must be enabled or disabled
  12600. */
  12601. Engine.prototype.setStencilBuffer = function (enable) {
  12602. this._stencilState.stencilTest = enable;
  12603. };
  12604. /**
  12605. * Gets the current stencil mask
  12606. * @returns a number defining the new stencil mask to use
  12607. */
  12608. Engine.prototype.getStencilMask = function () {
  12609. return this._stencilState.stencilMask;
  12610. };
  12611. /**
  12612. * Sets the current stencil mask
  12613. * @param mask defines the new stencil mask to use
  12614. */
  12615. Engine.prototype.setStencilMask = function (mask) {
  12616. this._stencilState.stencilMask = mask;
  12617. };
  12618. /**
  12619. * Gets the current stencil function
  12620. * @returns a number defining the stencil function to use
  12621. */
  12622. Engine.prototype.getStencilFunction = function () {
  12623. return this._stencilState.stencilFunc;
  12624. };
  12625. /**
  12626. * Gets the current stencil reference value
  12627. * @returns a number defining the stencil reference value to use
  12628. */
  12629. Engine.prototype.getStencilFunctionReference = function () {
  12630. return this._stencilState.stencilFuncRef;
  12631. };
  12632. /**
  12633. * Gets the current stencil mask
  12634. * @returns a number defining the stencil mask to use
  12635. */
  12636. Engine.prototype.getStencilFunctionMask = function () {
  12637. return this._stencilState.stencilFuncMask;
  12638. };
  12639. /**
  12640. * Sets the current stencil function
  12641. * @param stencilFunc defines the new stencil function to use
  12642. */
  12643. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12644. this._stencilState.stencilFunc = stencilFunc;
  12645. };
  12646. /**
  12647. * Sets the current stencil reference
  12648. * @param reference defines the new stencil reference to use
  12649. */
  12650. Engine.prototype.setStencilFunctionReference = function (reference) {
  12651. this._stencilState.stencilFuncRef = reference;
  12652. };
  12653. /**
  12654. * Sets the current stencil mask
  12655. * @param mask defines the new stencil mask to use
  12656. */
  12657. Engine.prototype.setStencilFunctionMask = function (mask) {
  12658. this._stencilState.stencilFuncMask = mask;
  12659. };
  12660. /**
  12661. * Gets the current stencil operation when stencil fails
  12662. * @returns a number defining stencil operation to use when stencil fails
  12663. */
  12664. Engine.prototype.getStencilOperationFail = function () {
  12665. return this._stencilState.stencilOpStencilFail;
  12666. };
  12667. /**
  12668. * Gets the current stencil operation when depth fails
  12669. * @returns a number defining stencil operation to use when depth fails
  12670. */
  12671. Engine.prototype.getStencilOperationDepthFail = function () {
  12672. return this._stencilState.stencilOpDepthFail;
  12673. };
  12674. /**
  12675. * Gets the current stencil operation when stencil passes
  12676. * @returns a number defining stencil operation to use when stencil passes
  12677. */
  12678. Engine.prototype.getStencilOperationPass = function () {
  12679. return this._stencilState.stencilOpStencilDepthPass;
  12680. };
  12681. /**
  12682. * Sets the stencil operation to use when stencil fails
  12683. * @param operation defines the stencil operation to use when stencil fails
  12684. */
  12685. Engine.prototype.setStencilOperationFail = function (operation) {
  12686. this._stencilState.stencilOpStencilFail = operation;
  12687. };
  12688. /**
  12689. * Sets the stencil operation to use when depth fails
  12690. * @param operation defines the stencil operation to use when depth fails
  12691. */
  12692. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12693. this._stencilState.stencilOpDepthFail = operation;
  12694. };
  12695. /**
  12696. * Sets the stencil operation to use when stencil passes
  12697. * @param operation defines the stencil operation to use when stencil passes
  12698. */
  12699. Engine.prototype.setStencilOperationPass = function (operation) {
  12700. this._stencilState.stencilOpStencilDepthPass = operation;
  12701. };
  12702. /**
  12703. * Sets a boolean indicating if the dithering state is enabled or disabled
  12704. * @param value defines the dithering state
  12705. */
  12706. Engine.prototype.setDitheringState = function (value) {
  12707. if (value) {
  12708. this._gl.enable(this._gl.DITHER);
  12709. }
  12710. else {
  12711. this._gl.disable(this._gl.DITHER);
  12712. }
  12713. };
  12714. /**
  12715. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12716. * @param value defines the rasterizer state
  12717. */
  12718. Engine.prototype.setRasterizerState = function (value) {
  12719. if (value) {
  12720. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12721. }
  12722. else {
  12723. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12724. }
  12725. };
  12726. /**
  12727. * stop executing a render loop function and remove it from the execution array
  12728. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12729. */
  12730. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12731. if (!renderFunction) {
  12732. this._activeRenderLoops = [];
  12733. return;
  12734. }
  12735. var index = this._activeRenderLoops.indexOf(renderFunction);
  12736. if (index >= 0) {
  12737. this._activeRenderLoops.splice(index, 1);
  12738. }
  12739. };
  12740. /** @hidden */
  12741. Engine.prototype._renderLoop = function () {
  12742. if (!this._contextWasLost) {
  12743. var shouldRender = true;
  12744. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12745. shouldRender = false;
  12746. }
  12747. if (shouldRender) {
  12748. // Start new frame
  12749. this.beginFrame();
  12750. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12751. var renderFunction = this._activeRenderLoops[index];
  12752. renderFunction();
  12753. }
  12754. // Present
  12755. this.endFrame();
  12756. }
  12757. }
  12758. if (this._activeRenderLoops.length > 0) {
  12759. // Register new frame
  12760. var requester = null;
  12761. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12762. requester = this._vrDisplay;
  12763. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12764. }
  12765. else {
  12766. this._renderingQueueLaunched = false;
  12767. }
  12768. };
  12769. /**
  12770. * Register and execute a render loop. The engine can have more than one render function
  12771. * @param renderFunction defines the function to continuously execute
  12772. */
  12773. Engine.prototype.runRenderLoop = function (renderFunction) {
  12774. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12775. return;
  12776. }
  12777. this._activeRenderLoops.push(renderFunction);
  12778. if (!this._renderingQueueLaunched) {
  12779. this._renderingQueueLaunched = true;
  12780. this._bindedRenderFunction = this._renderLoop.bind(this);
  12781. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12782. }
  12783. };
  12784. /**
  12785. * Toggle full screen mode
  12786. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12787. * @param options defines an option object to be sent to the requestFullscreen function
  12788. */
  12789. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12790. if (this.isFullscreen) {
  12791. BABYLON.Tools.ExitFullscreen();
  12792. }
  12793. else {
  12794. this._pointerLockRequested = requestPointerLock;
  12795. if (this._renderingCanvas) {
  12796. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12797. }
  12798. }
  12799. };
  12800. /**
  12801. * Clear the current render buffer or the current render target (if any is set up)
  12802. * @param color defines the color to use
  12803. * @param backBuffer defines if the back buffer must be cleared
  12804. * @param depth defines if the depth buffer must be cleared
  12805. * @param stencil defines if the stencil buffer must be cleared
  12806. */
  12807. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12808. if (stencil === void 0) { stencil = false; }
  12809. this.applyStates();
  12810. var mode = 0;
  12811. if (backBuffer && color) {
  12812. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12813. mode |= this._gl.COLOR_BUFFER_BIT;
  12814. }
  12815. if (depth) {
  12816. this._gl.clearDepth(1.0);
  12817. mode |= this._gl.DEPTH_BUFFER_BIT;
  12818. }
  12819. if (stencil) {
  12820. this._gl.clearStencil(0);
  12821. mode |= this._gl.STENCIL_BUFFER_BIT;
  12822. }
  12823. this._gl.clear(mode);
  12824. };
  12825. /**
  12826. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12827. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12828. * @param y defines the y-coordinate of the corner of the clear rectangle
  12829. * @param width defines the width of the clear rectangle
  12830. * @param height defines the height of the clear rectangle
  12831. * @param clearColor defines the clear color
  12832. */
  12833. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12834. var gl = this._gl;
  12835. // Save state
  12836. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12837. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12838. // Change state
  12839. gl.enable(gl.SCISSOR_TEST);
  12840. gl.scissor(x, y, width, height);
  12841. // Clear
  12842. this.clear(clearColor, true, true, true);
  12843. // Restore state
  12844. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12845. if (curScissor === true) {
  12846. gl.enable(gl.SCISSOR_TEST);
  12847. }
  12848. else {
  12849. gl.disable(gl.SCISSOR_TEST);
  12850. }
  12851. };
  12852. /**
  12853. * Set the WebGL's viewport
  12854. * @param viewport defines the viewport element to be used
  12855. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12856. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12857. */
  12858. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12859. var width = requiredWidth || this.getRenderWidth();
  12860. var height = requiredHeight || this.getRenderHeight();
  12861. var x = viewport.x || 0;
  12862. var y = viewport.y || 0;
  12863. this._cachedViewport = viewport;
  12864. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12865. };
  12866. /**
  12867. * Directly set the WebGL Viewport
  12868. * @param x defines the x coordinate of the viewport (in screen space)
  12869. * @param y defines the y coordinate of the viewport (in screen space)
  12870. * @param width defines the width of the viewport (in screen space)
  12871. * @param height defines the height of the viewport (in screen space)
  12872. * @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
  12873. */
  12874. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12875. var currentViewport = this._cachedViewport;
  12876. this._cachedViewport = null;
  12877. this._gl.viewport(x, y, width, height);
  12878. return currentViewport;
  12879. };
  12880. /**
  12881. * Begin a new frame
  12882. */
  12883. Engine.prototype.beginFrame = function () {
  12884. this.onBeginFrameObservable.notifyObservers(this);
  12885. this._measureFps();
  12886. };
  12887. /**
  12888. * Enf the current frame
  12889. */
  12890. Engine.prototype.endFrame = function () {
  12891. // Force a flush in case we are using a bad OS.
  12892. if (this._badOS) {
  12893. this.flushFramebuffer();
  12894. }
  12895. // Submit frame to the vr device, if enabled
  12896. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12897. // TODO: We should only submit the frame if we read frameData successfully.
  12898. this._vrDisplay.submitFrame();
  12899. }
  12900. this.onEndFrameObservable.notifyObservers(this);
  12901. };
  12902. /**
  12903. * Resize the view according to the canvas' size
  12904. */
  12905. Engine.prototype.resize = function () {
  12906. // We're not resizing the size of the canvas while in VR mode & presenting
  12907. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12908. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12909. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12910. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12911. }
  12912. };
  12913. /**
  12914. * Force a specific size of the canvas
  12915. * @param width defines the new canvas' width
  12916. * @param height defines the new canvas' height
  12917. */
  12918. Engine.prototype.setSize = function (width, height) {
  12919. if (!this._renderingCanvas) {
  12920. return;
  12921. }
  12922. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12923. return;
  12924. }
  12925. this._renderingCanvas.width = width;
  12926. this._renderingCanvas.height = height;
  12927. for (var index = 0; index < this.scenes.length; index++) {
  12928. var scene = this.scenes[index];
  12929. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12930. var cam = scene.cameras[camIndex];
  12931. cam._currentRenderId = 0;
  12932. }
  12933. }
  12934. if (this.onResizeObservable.hasObservers) {
  12935. this.onResizeObservable.notifyObservers(this);
  12936. }
  12937. };
  12938. // WebVR functions
  12939. /**
  12940. * Gets a boolean indicating if a webVR device was detected
  12941. * @returns true if a webVR device was detected
  12942. */
  12943. Engine.prototype.isVRDevicePresent = function () {
  12944. return !!this._vrDisplay;
  12945. };
  12946. /**
  12947. * Gets the current webVR device
  12948. * @returns the current webVR device (or null)
  12949. */
  12950. Engine.prototype.getVRDevice = function () {
  12951. return this._vrDisplay;
  12952. };
  12953. /**
  12954. * Initializes a webVR display and starts listening to display change events
  12955. * The onVRDisplayChangedObservable will be notified upon these changes
  12956. * @returns The onVRDisplayChangedObservable
  12957. */
  12958. Engine.prototype.initWebVR = function () {
  12959. this.initWebVRAsync();
  12960. return this.onVRDisplayChangedObservable;
  12961. };
  12962. /**
  12963. * Initializes a webVR display and starts listening to display change events
  12964. * The onVRDisplayChangedObservable will be notified upon these changes
  12965. * @returns A promise containing a VRDisplay and if vr is supported
  12966. */
  12967. Engine.prototype.initWebVRAsync = function () {
  12968. var _this = this;
  12969. var notifyObservers = function () {
  12970. var eventArgs = {
  12971. vrDisplay: _this._vrDisplay,
  12972. vrSupported: _this._vrSupported
  12973. };
  12974. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12975. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12976. };
  12977. if (!this._onVrDisplayConnect) {
  12978. this._onVrDisplayConnect = function (event) {
  12979. _this._vrDisplay = event.display;
  12980. notifyObservers();
  12981. };
  12982. this._onVrDisplayDisconnect = function () {
  12983. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12984. _this._vrDisplay = undefined;
  12985. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12986. notifyObservers();
  12987. };
  12988. this._onVrDisplayPresentChange = function () {
  12989. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12990. };
  12991. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12992. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12993. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12994. }
  12995. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12996. this._webVRInitPromise.then(notifyObservers);
  12997. return this._webVRInitPromise;
  12998. };
  12999. /**
  13000. * Call this function to switch to webVR mode
  13001. * Will do nothing if webVR is not supported or if there is no webVR device
  13002. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13003. */
  13004. Engine.prototype.enableVR = function () {
  13005. var _this = this;
  13006. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13007. var onResolved = function () {
  13008. _this.onVRRequestPresentComplete.notifyObservers(true);
  13009. _this._onVRFullScreenTriggered();
  13010. };
  13011. var onRejected = function () {
  13012. _this.onVRRequestPresentComplete.notifyObservers(false);
  13013. };
  13014. this.onVRRequestPresentStart.notifyObservers(this);
  13015. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13016. }
  13017. };
  13018. /**
  13019. * Call this function to leave webVR mode
  13020. * Will do nothing if webVR is not supported or if there is no webVR device
  13021. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13022. */
  13023. Engine.prototype.disableVR = function () {
  13024. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13025. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13026. }
  13027. };
  13028. Engine.prototype._getVRDisplaysAsync = function () {
  13029. var _this = this;
  13030. return new Promise(function (res, rej) {
  13031. if (navigator.getVRDisplays) {
  13032. navigator.getVRDisplays().then(function (devices) {
  13033. _this._vrSupported = true;
  13034. // note that devices may actually be an empty array. This is fine;
  13035. // we expect this._vrDisplay to be undefined in this case.
  13036. _this._vrDisplay = devices[0];
  13037. res({
  13038. vrDisplay: _this._vrDisplay,
  13039. vrSupported: _this._vrSupported
  13040. });
  13041. });
  13042. }
  13043. else {
  13044. _this._vrDisplay = undefined;
  13045. _this._vrSupported = false;
  13046. res({
  13047. vrDisplay: _this._vrDisplay,
  13048. vrSupported: _this._vrSupported
  13049. });
  13050. }
  13051. });
  13052. };
  13053. /**
  13054. * Binds the frame buffer to the specified texture.
  13055. * @param texture The texture to render to or null for the default canvas
  13056. * @param faceIndex The face of the texture to render to in case of cube texture
  13057. * @param requiredWidth The width of the target to render to
  13058. * @param requiredHeight The height of the target to render to
  13059. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13060. * @param depthStencilTexture The depth stencil texture to use to render
  13061. */
  13062. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13063. if (this._currentRenderTarget) {
  13064. this.unBindFramebuffer(this._currentRenderTarget);
  13065. }
  13066. this._currentRenderTarget = texture;
  13067. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13068. var gl = this._gl;
  13069. if (texture.isCube) {
  13070. if (faceIndex === undefined) {
  13071. faceIndex = 0;
  13072. }
  13073. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13074. if (depthStencilTexture) {
  13075. if (depthStencilTexture._generateStencilBuffer) {
  13076. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13077. }
  13078. else {
  13079. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13080. }
  13081. }
  13082. }
  13083. if (this._cachedViewport && !forceFullscreenViewport) {
  13084. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13085. }
  13086. else {
  13087. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13088. }
  13089. this.wipeCaches();
  13090. };
  13091. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13092. if (this._currentFramebuffer !== framebuffer) {
  13093. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13094. this._currentFramebuffer = framebuffer;
  13095. }
  13096. };
  13097. /**
  13098. * Unbind the current render target texture from the webGL context
  13099. * @param texture defines the render target texture to unbind
  13100. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13101. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13102. */
  13103. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13104. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13105. this._currentRenderTarget = null;
  13106. // If MSAA, we need to bitblt back to main texture
  13107. var gl = this._gl;
  13108. if (texture._MSAAFramebuffer) {
  13109. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13110. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13111. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13112. }
  13113. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13114. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13115. gl.generateMipmap(gl.TEXTURE_2D);
  13116. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13117. }
  13118. if (onBeforeUnbind) {
  13119. if (texture._MSAAFramebuffer) {
  13120. // Bind the correct framebuffer
  13121. this.bindUnboundFramebuffer(texture._framebuffer);
  13122. }
  13123. onBeforeUnbind();
  13124. }
  13125. this.bindUnboundFramebuffer(null);
  13126. };
  13127. /**
  13128. * Unbind a list of render target textures from the webGL context
  13129. * This is used only when drawBuffer extension or webGL2 are active
  13130. * @param textures defines the render target textures to unbind
  13131. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13132. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13133. */
  13134. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13135. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13136. this._currentRenderTarget = null;
  13137. // If MSAA, we need to bitblt back to main texture
  13138. var gl = this._gl;
  13139. if (textures[0]._MSAAFramebuffer) {
  13140. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13141. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13142. var attachments = textures[0]._attachments;
  13143. if (!attachments) {
  13144. attachments = new Array(textures.length);
  13145. textures[0]._attachments = attachments;
  13146. }
  13147. for (var i = 0; i < textures.length; i++) {
  13148. var texture = textures[i];
  13149. for (var j = 0; j < attachments.length; j++) {
  13150. attachments[j] = gl.NONE;
  13151. }
  13152. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13153. gl.readBuffer(attachments[i]);
  13154. gl.drawBuffers(attachments);
  13155. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13156. }
  13157. for (var i = 0; i < attachments.length; i++) {
  13158. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13159. }
  13160. gl.drawBuffers(attachments);
  13161. }
  13162. for (var i = 0; i < textures.length; i++) {
  13163. var texture = textures[i];
  13164. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13165. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13166. gl.generateMipmap(gl.TEXTURE_2D);
  13167. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13168. }
  13169. }
  13170. if (onBeforeUnbind) {
  13171. if (textures[0]._MSAAFramebuffer) {
  13172. // Bind the correct framebuffer
  13173. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13174. }
  13175. onBeforeUnbind();
  13176. }
  13177. this.bindUnboundFramebuffer(null);
  13178. };
  13179. /**
  13180. * Force the mipmap generation for the given render target texture
  13181. * @param texture defines the render target texture to use
  13182. */
  13183. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13184. if (texture.generateMipMaps) {
  13185. var gl = this._gl;
  13186. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13187. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13188. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13189. }
  13190. };
  13191. /**
  13192. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13193. */
  13194. Engine.prototype.flushFramebuffer = function () {
  13195. this._gl.flush();
  13196. };
  13197. /**
  13198. * Unbind the current render target and bind the default framebuffer
  13199. */
  13200. Engine.prototype.restoreDefaultFramebuffer = function () {
  13201. if (this._currentRenderTarget) {
  13202. this.unBindFramebuffer(this._currentRenderTarget);
  13203. }
  13204. else {
  13205. this.bindUnboundFramebuffer(null);
  13206. }
  13207. if (this._cachedViewport) {
  13208. this.setViewport(this._cachedViewport);
  13209. }
  13210. this.wipeCaches();
  13211. };
  13212. // UBOs
  13213. /**
  13214. * Create an uniform buffer
  13215. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13216. * @param elements defines the content of the uniform buffer
  13217. * @returns the webGL uniform buffer
  13218. */
  13219. Engine.prototype.createUniformBuffer = function (elements) {
  13220. var ubo = this._gl.createBuffer();
  13221. if (!ubo) {
  13222. throw new Error("Unable to create uniform buffer");
  13223. }
  13224. this.bindUniformBuffer(ubo);
  13225. if (elements instanceof Float32Array) {
  13226. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13227. }
  13228. else {
  13229. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13230. }
  13231. this.bindUniformBuffer(null);
  13232. ubo.references = 1;
  13233. return ubo;
  13234. };
  13235. /**
  13236. * Create a dynamic uniform buffer
  13237. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13238. * @param elements defines the content of the uniform buffer
  13239. * @returns the webGL uniform buffer
  13240. */
  13241. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13242. var ubo = this._gl.createBuffer();
  13243. if (!ubo) {
  13244. throw new Error("Unable to create dynamic uniform buffer");
  13245. }
  13246. this.bindUniformBuffer(ubo);
  13247. if (elements instanceof Float32Array) {
  13248. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13249. }
  13250. else {
  13251. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13252. }
  13253. this.bindUniformBuffer(null);
  13254. ubo.references = 1;
  13255. return ubo;
  13256. };
  13257. /**
  13258. * Update an existing uniform buffer
  13259. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13260. * @param uniformBuffer defines the target uniform buffer
  13261. * @param elements defines the content to update
  13262. * @param offset defines the offset in the uniform buffer where update should start
  13263. * @param count defines the size of the data to update
  13264. */
  13265. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13266. this.bindUniformBuffer(uniformBuffer);
  13267. if (offset === undefined) {
  13268. offset = 0;
  13269. }
  13270. if (count === undefined) {
  13271. if (elements instanceof Float32Array) {
  13272. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13273. }
  13274. else {
  13275. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13276. }
  13277. }
  13278. else {
  13279. if (elements instanceof Float32Array) {
  13280. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13281. }
  13282. else {
  13283. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13284. }
  13285. }
  13286. this.bindUniformBuffer(null);
  13287. };
  13288. // VBOs
  13289. Engine.prototype._resetVertexBufferBinding = function () {
  13290. this.bindArrayBuffer(null);
  13291. this._cachedVertexBuffers = null;
  13292. };
  13293. /**
  13294. * Creates a vertex buffer
  13295. * @param data the data for the vertex buffer
  13296. * @returns the new WebGL static buffer
  13297. */
  13298. Engine.prototype.createVertexBuffer = function (data) {
  13299. var vbo = this._gl.createBuffer();
  13300. if (!vbo) {
  13301. throw new Error("Unable to create vertex buffer");
  13302. }
  13303. this.bindArrayBuffer(vbo);
  13304. if (data instanceof Array) {
  13305. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13306. }
  13307. else {
  13308. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13309. }
  13310. this._resetVertexBufferBinding();
  13311. vbo.references = 1;
  13312. return vbo;
  13313. };
  13314. /**
  13315. * Creates a dynamic vertex buffer
  13316. * @param data the data for the dynamic vertex buffer
  13317. * @returns the new WebGL dynamic buffer
  13318. */
  13319. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13320. var vbo = this._gl.createBuffer();
  13321. if (!vbo) {
  13322. throw new Error("Unable to create dynamic vertex buffer");
  13323. }
  13324. this.bindArrayBuffer(vbo);
  13325. if (data instanceof Array) {
  13326. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13327. }
  13328. else {
  13329. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13330. }
  13331. this._resetVertexBufferBinding();
  13332. vbo.references = 1;
  13333. return vbo;
  13334. };
  13335. /**
  13336. * Update a dynamic index buffer
  13337. * @param indexBuffer defines the target index buffer
  13338. * @param indices defines the data to update
  13339. * @param offset defines the offset in the target index buffer where update should start
  13340. */
  13341. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13342. if (offset === void 0) { offset = 0; }
  13343. // Force cache update
  13344. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13345. this.bindIndexBuffer(indexBuffer);
  13346. var arrayBuffer;
  13347. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13348. arrayBuffer = indices;
  13349. }
  13350. else {
  13351. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13352. }
  13353. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13354. this._resetIndexBufferBinding();
  13355. };
  13356. /**
  13357. * Updates a dynamic vertex buffer.
  13358. * @param vertexBuffer the vertex buffer to update
  13359. * @param data the data used to update the vertex buffer
  13360. * @param byteOffset the byte offset of the data
  13361. * @param byteLength the byte length of the data
  13362. */
  13363. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13364. this.bindArrayBuffer(vertexBuffer);
  13365. if (byteOffset === undefined) {
  13366. byteOffset = 0;
  13367. }
  13368. if (byteLength === undefined) {
  13369. if (data instanceof Array) {
  13370. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13371. }
  13372. else {
  13373. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13374. }
  13375. }
  13376. else {
  13377. if (data instanceof Array) {
  13378. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13379. }
  13380. else {
  13381. if (data instanceof ArrayBuffer) {
  13382. data = new Uint8Array(data, byteOffset, byteLength);
  13383. }
  13384. else {
  13385. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13386. }
  13387. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13388. }
  13389. }
  13390. this._resetVertexBufferBinding();
  13391. };
  13392. Engine.prototype._resetIndexBufferBinding = function () {
  13393. this.bindIndexBuffer(null);
  13394. this._cachedIndexBuffer = null;
  13395. };
  13396. /**
  13397. * Creates a new index buffer
  13398. * @param indices defines the content of the index buffer
  13399. * @param updatable defines if the index buffer must be updatable
  13400. * @returns a new webGL buffer
  13401. */
  13402. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13403. var vbo = this._gl.createBuffer();
  13404. if (!vbo) {
  13405. throw new Error("Unable to create index buffer");
  13406. }
  13407. this.bindIndexBuffer(vbo);
  13408. // Check for 32 bits indices
  13409. var arrayBuffer;
  13410. var need32Bits = false;
  13411. if (indices instanceof Uint16Array) {
  13412. arrayBuffer = indices;
  13413. }
  13414. else {
  13415. //check 32 bit support
  13416. if (this._caps.uintIndices) {
  13417. if (indices instanceof Uint32Array) {
  13418. arrayBuffer = indices;
  13419. need32Bits = true;
  13420. }
  13421. else {
  13422. //number[] or Int32Array, check if 32 bit is necessary
  13423. for (var index = 0; index < indices.length; index++) {
  13424. if (indices[index] > 65535) {
  13425. need32Bits = true;
  13426. break;
  13427. }
  13428. }
  13429. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13430. }
  13431. }
  13432. else {
  13433. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13434. arrayBuffer = new Uint16Array(indices);
  13435. }
  13436. }
  13437. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13438. this._resetIndexBufferBinding();
  13439. vbo.references = 1;
  13440. vbo.is32Bits = need32Bits;
  13441. return vbo;
  13442. };
  13443. /**
  13444. * Bind a webGL buffer to the webGL context
  13445. * @param buffer defines the buffer to bind
  13446. */
  13447. Engine.prototype.bindArrayBuffer = function (buffer) {
  13448. if (!this._vaoRecordInProgress) {
  13449. this._unbindVertexArrayObject();
  13450. }
  13451. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13452. };
  13453. /**
  13454. * Bind an uniform buffer to the current webGL context
  13455. * @param buffer defines the buffer to bind
  13456. */
  13457. Engine.prototype.bindUniformBuffer = function (buffer) {
  13458. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13459. };
  13460. /**
  13461. * Bind a buffer to the current webGL context at a given location
  13462. * @param buffer defines the buffer to bind
  13463. * @param location defines the index where to bind the buffer
  13464. */
  13465. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13466. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13467. };
  13468. /**
  13469. * Bind a specific block at a given index in a specific shader program
  13470. * @param shaderProgram defines the shader program
  13471. * @param blockName defines the block name
  13472. * @param index defines the index where to bind the block
  13473. */
  13474. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13475. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13476. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13477. };
  13478. ;
  13479. Engine.prototype.bindIndexBuffer = function (buffer) {
  13480. if (!this._vaoRecordInProgress) {
  13481. this._unbindVertexArrayObject();
  13482. }
  13483. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13484. };
  13485. Engine.prototype.bindBuffer = function (buffer, target) {
  13486. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13487. this._gl.bindBuffer(target, buffer);
  13488. this._currentBoundBuffer[target] = buffer;
  13489. }
  13490. };
  13491. /**
  13492. * update the bound buffer with the given data
  13493. * @param data defines the data to update
  13494. */
  13495. Engine.prototype.updateArrayBuffer = function (data) {
  13496. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13497. };
  13498. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13499. var pointer = this._currentBufferPointers[indx];
  13500. var changed = false;
  13501. if (!pointer.active) {
  13502. changed = true;
  13503. pointer.active = true;
  13504. pointer.index = indx;
  13505. pointer.size = size;
  13506. pointer.type = type;
  13507. pointer.normalized = normalized;
  13508. pointer.stride = stride;
  13509. pointer.offset = offset;
  13510. pointer.buffer = buffer;
  13511. }
  13512. else {
  13513. if (pointer.buffer !== buffer) {
  13514. pointer.buffer = buffer;
  13515. changed = true;
  13516. }
  13517. if (pointer.size !== size) {
  13518. pointer.size = size;
  13519. changed = true;
  13520. }
  13521. if (pointer.type !== type) {
  13522. pointer.type = type;
  13523. changed = true;
  13524. }
  13525. if (pointer.normalized !== normalized) {
  13526. pointer.normalized = normalized;
  13527. changed = true;
  13528. }
  13529. if (pointer.stride !== stride) {
  13530. pointer.stride = stride;
  13531. changed = true;
  13532. }
  13533. if (pointer.offset !== offset) {
  13534. pointer.offset = offset;
  13535. changed = true;
  13536. }
  13537. }
  13538. if (changed || this._vaoRecordInProgress) {
  13539. this.bindArrayBuffer(buffer);
  13540. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13541. }
  13542. };
  13543. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13544. if (indexBuffer == null) {
  13545. return;
  13546. }
  13547. if (this._cachedIndexBuffer !== indexBuffer) {
  13548. this._cachedIndexBuffer = indexBuffer;
  13549. this.bindIndexBuffer(indexBuffer);
  13550. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13551. }
  13552. };
  13553. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13554. var attributes = effect.getAttributesNames();
  13555. if (!this._vaoRecordInProgress) {
  13556. this._unbindVertexArrayObject();
  13557. }
  13558. this.unbindAllAttributes();
  13559. for (var index = 0; index < attributes.length; index++) {
  13560. var order = effect.getAttributeLocation(index);
  13561. if (order >= 0) {
  13562. var vertexBuffer = vertexBuffers[attributes[index]];
  13563. if (!vertexBuffer) {
  13564. continue;
  13565. }
  13566. this._gl.enableVertexAttribArray(order);
  13567. if (!this._vaoRecordInProgress) {
  13568. this._vertexAttribArraysEnabled[order] = true;
  13569. }
  13570. var buffer = vertexBuffer.getBuffer();
  13571. if (buffer) {
  13572. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13573. if (vertexBuffer.getIsInstanced()) {
  13574. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13575. if (!this._vaoRecordInProgress) {
  13576. this._currentInstanceLocations.push(order);
  13577. this._currentInstanceBuffers.push(buffer);
  13578. }
  13579. }
  13580. }
  13581. }
  13582. }
  13583. };
  13584. /**
  13585. * Records a vertex array object
  13586. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13587. * @param vertexBuffers defines the list of vertex buffers to store
  13588. * @param indexBuffer defines the index buffer to store
  13589. * @param effect defines the effect to store
  13590. * @returns the new vertex array object
  13591. */
  13592. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13593. var vao = this._gl.createVertexArray();
  13594. this._vaoRecordInProgress = true;
  13595. this._gl.bindVertexArray(vao);
  13596. this._mustWipeVertexAttributes = true;
  13597. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13598. this.bindIndexBuffer(indexBuffer);
  13599. this._vaoRecordInProgress = false;
  13600. this._gl.bindVertexArray(null);
  13601. return vao;
  13602. };
  13603. /**
  13604. * Bind a specific vertex array object
  13605. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13606. * @param vertexArrayObject defines the vertex array object to bind
  13607. * @param indexBuffer defines the index buffer to bind
  13608. */
  13609. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13610. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13611. this._cachedVertexArrayObject = vertexArrayObject;
  13612. this._gl.bindVertexArray(vertexArrayObject);
  13613. this._cachedVertexBuffers = null;
  13614. this._cachedIndexBuffer = null;
  13615. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13616. this._mustWipeVertexAttributes = true;
  13617. }
  13618. };
  13619. /**
  13620. * Bind webGl buffers directly to the webGL context
  13621. * @param vertexBuffer defines the vertex buffer to bind
  13622. * @param indexBuffer defines the index buffer to bind
  13623. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13624. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13625. * @param effect defines the effect associated with the vertex buffer
  13626. */
  13627. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13628. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13629. this._cachedVertexBuffers = vertexBuffer;
  13630. this._cachedEffectForVertexBuffers = effect;
  13631. var attributesCount = effect.getAttributesCount();
  13632. this._unbindVertexArrayObject();
  13633. this.unbindAllAttributes();
  13634. var offset = 0;
  13635. for (var index = 0; index < attributesCount; index++) {
  13636. if (index < vertexDeclaration.length) {
  13637. var order = effect.getAttributeLocation(index);
  13638. if (order >= 0) {
  13639. this._gl.enableVertexAttribArray(order);
  13640. this._vertexAttribArraysEnabled[order] = true;
  13641. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13642. }
  13643. offset += vertexDeclaration[index] * 4;
  13644. }
  13645. }
  13646. }
  13647. this._bindIndexBufferWithCache(indexBuffer);
  13648. };
  13649. Engine.prototype._unbindVertexArrayObject = function () {
  13650. if (!this._cachedVertexArrayObject) {
  13651. return;
  13652. }
  13653. this._cachedVertexArrayObject = null;
  13654. this._gl.bindVertexArray(null);
  13655. };
  13656. /**
  13657. * Bind a list of vertex buffers to the webGL context
  13658. * @param vertexBuffers defines the list of vertex buffers to bind
  13659. * @param indexBuffer defines the index buffer to bind
  13660. * @param effect defines the effect associated with the vertex buffers
  13661. */
  13662. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13663. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13664. this._cachedVertexBuffers = vertexBuffers;
  13665. this._cachedEffectForVertexBuffers = effect;
  13666. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13667. }
  13668. this._bindIndexBufferWithCache(indexBuffer);
  13669. };
  13670. /**
  13671. * Unbind all instance attributes
  13672. */
  13673. Engine.prototype.unbindInstanceAttributes = function () {
  13674. var boundBuffer;
  13675. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13676. var instancesBuffer = this._currentInstanceBuffers[i];
  13677. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13678. boundBuffer = instancesBuffer;
  13679. this.bindArrayBuffer(instancesBuffer);
  13680. }
  13681. var offsetLocation = this._currentInstanceLocations[i];
  13682. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13683. }
  13684. this._currentInstanceBuffers.length = 0;
  13685. this._currentInstanceLocations.length = 0;
  13686. };
  13687. /**
  13688. * Release and free the memory of a vertex array object
  13689. * @param vao defines the vertex array object to delete
  13690. */
  13691. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13692. this._gl.deleteVertexArray(vao);
  13693. };
  13694. /** @hidden */
  13695. Engine.prototype._releaseBuffer = function (buffer) {
  13696. buffer.references--;
  13697. if (buffer.references === 0) {
  13698. this._gl.deleteBuffer(buffer);
  13699. return true;
  13700. }
  13701. return false;
  13702. };
  13703. /**
  13704. * Creates a webGL buffer to use with instanciation
  13705. * @param capacity defines the size of the buffer
  13706. * @returns the webGL buffer
  13707. */
  13708. Engine.prototype.createInstancesBuffer = function (capacity) {
  13709. var buffer = this._gl.createBuffer();
  13710. if (!buffer) {
  13711. throw new Error("Unable to create instance buffer");
  13712. }
  13713. buffer.capacity = capacity;
  13714. this.bindArrayBuffer(buffer);
  13715. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13716. return buffer;
  13717. };
  13718. /**
  13719. * Delete a webGL buffer used with instanciation
  13720. * @param buffer defines the webGL buffer to delete
  13721. */
  13722. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13723. this._gl.deleteBuffer(buffer);
  13724. };
  13725. /**
  13726. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13727. * @param instancesBuffer defines the webGL buffer to update and bind
  13728. * @param data defines the data to store in the buffer
  13729. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13730. */
  13731. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13732. this.bindArrayBuffer(instancesBuffer);
  13733. if (data) {
  13734. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13735. }
  13736. if (offsetLocations[0].index !== undefined) {
  13737. var stride = 0;
  13738. for (var i = 0; i < offsetLocations.length; i++) {
  13739. var ai = offsetLocations[i];
  13740. stride += ai.attributeSize * 4;
  13741. }
  13742. for (var i = 0; i < offsetLocations.length; i++) {
  13743. var ai = offsetLocations[i];
  13744. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13745. this._gl.enableVertexAttribArray(ai.index);
  13746. this._vertexAttribArraysEnabled[ai.index] = true;
  13747. }
  13748. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13749. this._gl.vertexAttribDivisor(ai.index, 1);
  13750. this._currentInstanceLocations.push(ai.index);
  13751. this._currentInstanceBuffers.push(instancesBuffer);
  13752. }
  13753. }
  13754. else {
  13755. for (var index = 0; index < 4; index++) {
  13756. var offsetLocation = offsetLocations[index];
  13757. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13758. this._gl.enableVertexAttribArray(offsetLocation);
  13759. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13760. }
  13761. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13762. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13763. this._currentInstanceLocations.push(offsetLocation);
  13764. this._currentInstanceBuffers.push(instancesBuffer);
  13765. }
  13766. }
  13767. };
  13768. /**
  13769. * Apply all cached states (depth, culling, stencil and alpha)
  13770. */
  13771. Engine.prototype.applyStates = function () {
  13772. this._depthCullingState.apply(this._gl);
  13773. this._stencilState.apply(this._gl);
  13774. this._alphaState.apply(this._gl);
  13775. };
  13776. /**
  13777. * Send a draw order
  13778. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13779. * @param indexStart defines the starting index
  13780. * @param indexCount defines the number of index to draw
  13781. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13782. */
  13783. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13784. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13785. };
  13786. /**
  13787. * Draw a list of points
  13788. * @param verticesStart defines the index of first vertex to draw
  13789. * @param verticesCount defines the count of vertices to draw
  13790. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13791. */
  13792. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13793. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13794. };
  13795. /**
  13796. * Draw a list of unindexed primitives
  13797. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13798. * @param verticesStart defines the index of first vertex to draw
  13799. * @param verticesCount defines the count of vertices to draw
  13800. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13801. */
  13802. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13803. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13804. };
  13805. /**
  13806. * Draw a list of indexed primitives
  13807. * @param fillMode defines the primitive to use
  13808. * @param indexStart defines the starting index
  13809. * @param indexCount defines the number of index to draw
  13810. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13811. */
  13812. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13813. // Apply states
  13814. this.applyStates();
  13815. this._drawCalls.addCount(1, false);
  13816. // Render
  13817. var drawMode = this._drawMode(fillMode);
  13818. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13819. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13820. if (instancesCount) {
  13821. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13822. }
  13823. else {
  13824. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13825. }
  13826. };
  13827. /**
  13828. * Draw a list of unindexed primitives
  13829. * @param fillMode defines the primitive to use
  13830. * @param verticesStart defines the index of first vertex to draw
  13831. * @param verticesCount defines the count of vertices to draw
  13832. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13833. */
  13834. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13835. // Apply states
  13836. this.applyStates();
  13837. this._drawCalls.addCount(1, false);
  13838. var drawMode = this._drawMode(fillMode);
  13839. if (instancesCount) {
  13840. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13841. }
  13842. else {
  13843. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13844. }
  13845. };
  13846. Engine.prototype._drawMode = function (fillMode) {
  13847. switch (fillMode) {
  13848. // Triangle views
  13849. case BABYLON.Material.TriangleFillMode:
  13850. return this._gl.TRIANGLES;
  13851. case BABYLON.Material.PointFillMode:
  13852. return this._gl.POINTS;
  13853. case BABYLON.Material.WireFrameFillMode:
  13854. return this._gl.LINES;
  13855. // Draw modes
  13856. case BABYLON.Material.PointListDrawMode:
  13857. return this._gl.POINTS;
  13858. case BABYLON.Material.LineListDrawMode:
  13859. return this._gl.LINES;
  13860. case BABYLON.Material.LineLoopDrawMode:
  13861. return this._gl.LINE_LOOP;
  13862. case BABYLON.Material.LineStripDrawMode:
  13863. return this._gl.LINE_STRIP;
  13864. case BABYLON.Material.TriangleStripDrawMode:
  13865. return this._gl.TRIANGLE_STRIP;
  13866. case BABYLON.Material.TriangleFanDrawMode:
  13867. return this._gl.TRIANGLE_FAN;
  13868. default:
  13869. return this._gl.TRIANGLES;
  13870. }
  13871. };
  13872. // Shaders
  13873. /** @hidden */
  13874. Engine.prototype._releaseEffect = function (effect) {
  13875. if (this._compiledEffects[effect._key]) {
  13876. delete this._compiledEffects[effect._key];
  13877. this._deleteProgram(effect.getProgram());
  13878. }
  13879. };
  13880. /** @hidden */
  13881. Engine.prototype._deleteProgram = function (program) {
  13882. if (program) {
  13883. program.__SPECTOR_rebuildProgram = null;
  13884. if (program.transformFeedback) {
  13885. this.deleteTransformFeedback(program.transformFeedback);
  13886. program.transformFeedback = null;
  13887. }
  13888. this._gl.deleteProgram(program);
  13889. }
  13890. };
  13891. /**
  13892. * Create a new effect (used to store vertex/fragment shaders)
  13893. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13894. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13895. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13896. * @param samplers defines an array of string used to represent textures
  13897. * @param defines defines the string containing the defines to use to compile the shaders
  13898. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13899. * @param onCompiled defines a function to call when the effect creation is successful
  13900. * @param onError defines a function to call when the effect creation has failed
  13901. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13902. * @returns the new Effect
  13903. */
  13904. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13905. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13906. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13907. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13908. if (this._compiledEffects[name]) {
  13909. var compiledEffect = this._compiledEffects[name];
  13910. if (onCompiled && compiledEffect.isReady()) {
  13911. onCompiled(compiledEffect);
  13912. }
  13913. return compiledEffect;
  13914. }
  13915. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13916. effect._key = name;
  13917. this._compiledEffects[name] = effect;
  13918. return effect;
  13919. };
  13920. /**
  13921. * Create an effect to use with particle systems
  13922. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13923. * @param uniformsNames defines a list of attribute names
  13924. * @param samplers defines an array of string used to represent textures
  13925. * @param defines defines the string containing the defines to use to compile the shaders
  13926. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13927. * @param onCompiled defines a function to call when the effect creation is successful
  13928. * @param onError defines a function to call when the effect creation has failed
  13929. * @returns the new Effect
  13930. */
  13931. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13932. if (uniformsNames === void 0) { uniformsNames = []; }
  13933. if (samplers === void 0) { samplers = []; }
  13934. if (defines === void 0) { defines = ""; }
  13935. return this.createEffect({
  13936. vertex: "particles",
  13937. fragmentElement: fragmentName
  13938. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13939. };
  13940. /**
  13941. * Directly creates a webGL program
  13942. * @param vertexCode defines the vertex shader code to use
  13943. * @param fragmentCode defines the fragment shader code to use
  13944. * @param context defines the webGL context to use (if not set, the current one will be used)
  13945. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13946. * @returns the new webGL program
  13947. */
  13948. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13949. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13950. context = context || this._gl;
  13951. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13952. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13953. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13954. };
  13955. /**
  13956. * Creates a webGL program
  13957. * @param vertexCode defines the vertex shader code to use
  13958. * @param fragmentCode defines the fragment shader code to use
  13959. * @param defines defines the string containing the defines to use to compile the shaders
  13960. * @param context defines the webGL context to use (if not set, the current one will be used)
  13961. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13962. * @returns the new webGL program
  13963. */
  13964. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13965. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13966. context = context || this._gl;
  13967. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13968. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13969. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13970. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13971. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13972. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13973. return program;
  13974. };
  13975. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13976. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13977. var shaderProgram = context.createProgram();
  13978. if (!shaderProgram) {
  13979. throw new Error("Unable to create program");
  13980. }
  13981. context.attachShader(shaderProgram, vertexShader);
  13982. context.attachShader(shaderProgram, fragmentShader);
  13983. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13984. var transformFeedback = this.createTransformFeedback();
  13985. this.bindTransformFeedback(transformFeedback);
  13986. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13987. shaderProgram.transformFeedback = transformFeedback;
  13988. }
  13989. context.linkProgram(shaderProgram);
  13990. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13991. this.bindTransformFeedback(null);
  13992. }
  13993. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13994. if (!linked) {
  13995. context.validateProgram(shaderProgram);
  13996. var error = context.getProgramInfoLog(shaderProgram);
  13997. if (error) {
  13998. throw new Error(error);
  13999. }
  14000. }
  14001. context.deleteShader(vertexShader);
  14002. context.deleteShader(fragmentShader);
  14003. return shaderProgram;
  14004. };
  14005. /**
  14006. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14007. * @param shaderProgram defines the webGL program to use
  14008. * @param uniformsNames defines the list of uniform names
  14009. * @returns an array of webGL uniform locations
  14010. */
  14011. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14012. var results = new Array();
  14013. for (var index = 0; index < uniformsNames.length; index++) {
  14014. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14015. }
  14016. return results;
  14017. };
  14018. /**
  14019. * Gets the lsit of active attributes for a given webGL program
  14020. * @param shaderProgram defines the webGL program to use
  14021. * @param attributesNames defines the list of attribute names to get
  14022. * @returns an array of indices indicating the offset of each attribute
  14023. */
  14024. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14025. var results = [];
  14026. for (var index = 0; index < attributesNames.length; index++) {
  14027. try {
  14028. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14029. }
  14030. catch (e) {
  14031. results.push(-1);
  14032. }
  14033. }
  14034. return results;
  14035. };
  14036. /**
  14037. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14038. * @param effect defines the effect to activate
  14039. */
  14040. Engine.prototype.enableEffect = function (effect) {
  14041. if (!effect) {
  14042. return;
  14043. }
  14044. // Use program
  14045. this.bindSamplers(effect);
  14046. this._currentEffect = effect;
  14047. if (effect.onBind) {
  14048. effect.onBind(effect);
  14049. }
  14050. effect.onBindObservable.notifyObservers(effect);
  14051. };
  14052. /**
  14053. * Set the value of an uniform to an array of int32
  14054. * @param uniform defines the webGL uniform location where to store the value
  14055. * @param array defines the array of int32 to store
  14056. */
  14057. Engine.prototype.setIntArray = function (uniform, array) {
  14058. if (!uniform)
  14059. return;
  14060. this._gl.uniform1iv(uniform, array);
  14061. };
  14062. /**
  14063. * Set the value of an uniform to an array of int32 (stored as vec2)
  14064. * @param uniform defines the webGL uniform location where to store the value
  14065. * @param array defines the array of int32 to store
  14066. */
  14067. Engine.prototype.setIntArray2 = function (uniform, array) {
  14068. if (!uniform || array.length % 2 !== 0)
  14069. return;
  14070. this._gl.uniform2iv(uniform, array);
  14071. };
  14072. /**
  14073. * Set the value of an uniform to an array of int32 (stored as vec3)
  14074. * @param uniform defines the webGL uniform location where to store the value
  14075. * @param array defines the array of int32 to store
  14076. */
  14077. Engine.prototype.setIntArray3 = function (uniform, array) {
  14078. if (!uniform || array.length % 3 !== 0)
  14079. return;
  14080. this._gl.uniform3iv(uniform, array);
  14081. };
  14082. /**
  14083. * Set the value of an uniform to an array of int32 (stored as vec4)
  14084. * @param uniform defines the webGL uniform location where to store the value
  14085. * @param array defines the array of int32 to store
  14086. */
  14087. Engine.prototype.setIntArray4 = function (uniform, array) {
  14088. if (!uniform || array.length % 4 !== 0)
  14089. return;
  14090. this._gl.uniform4iv(uniform, array);
  14091. };
  14092. /**
  14093. * Set the value of an uniform to an array of float32
  14094. * @param uniform defines the webGL uniform location where to store the value
  14095. * @param array defines the array of float32 to store
  14096. */
  14097. Engine.prototype.setFloatArray = function (uniform, array) {
  14098. if (!uniform)
  14099. return;
  14100. this._gl.uniform1fv(uniform, array);
  14101. };
  14102. /**
  14103. * Set the value of an uniform to an array of float32 (stored as vec2)
  14104. * @param uniform defines the webGL uniform location where to store the value
  14105. * @param array defines the array of float32 to store
  14106. */
  14107. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14108. if (!uniform || array.length % 2 !== 0)
  14109. return;
  14110. this._gl.uniform2fv(uniform, array);
  14111. };
  14112. /**
  14113. * Set the value of an uniform to an array of float32 (stored as vec3)
  14114. * @param uniform defines the webGL uniform location where to store the value
  14115. * @param array defines the array of float32 to store
  14116. */
  14117. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14118. if (!uniform || array.length % 3 !== 0)
  14119. return;
  14120. this._gl.uniform3fv(uniform, array);
  14121. };
  14122. /**
  14123. * Set the value of an uniform to an array of float32 (stored as vec4)
  14124. * @param uniform defines the webGL uniform location where to store the value
  14125. * @param array defines the array of float32 to store
  14126. */
  14127. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14128. if (!uniform || array.length % 4 !== 0)
  14129. return;
  14130. this._gl.uniform4fv(uniform, array);
  14131. };
  14132. /**
  14133. * Set the value of an uniform to an array of number
  14134. * @param uniform defines the webGL uniform location where to store the value
  14135. * @param array defines the array of number to store
  14136. */
  14137. Engine.prototype.setArray = function (uniform, array) {
  14138. if (!uniform)
  14139. return;
  14140. this._gl.uniform1fv(uniform, array);
  14141. };
  14142. /**
  14143. * Set the value of an uniform to an array of number (stored as vec2)
  14144. * @param uniform defines the webGL uniform location where to store the value
  14145. * @param array defines the array of number to store
  14146. */
  14147. Engine.prototype.setArray2 = function (uniform, array) {
  14148. if (!uniform || array.length % 2 !== 0)
  14149. return;
  14150. this._gl.uniform2fv(uniform, array);
  14151. };
  14152. /**
  14153. * Set the value of an uniform to an array of number (stored as vec3)
  14154. * @param uniform defines the webGL uniform location where to store the value
  14155. * @param array defines the array of number to store
  14156. */
  14157. Engine.prototype.setArray3 = function (uniform, array) {
  14158. if (!uniform || array.length % 3 !== 0)
  14159. return;
  14160. this._gl.uniform3fv(uniform, array);
  14161. };
  14162. /**
  14163. * Set the value of an uniform to an array of number (stored as vec4)
  14164. * @param uniform defines the webGL uniform location where to store the value
  14165. * @param array defines the array of number to store
  14166. */
  14167. Engine.prototype.setArray4 = function (uniform, array) {
  14168. if (!uniform || array.length % 4 !== 0)
  14169. return;
  14170. this._gl.uniform4fv(uniform, array);
  14171. };
  14172. /**
  14173. * Set the value of an uniform to an array of float32 (stored as matrices)
  14174. * @param uniform defines the webGL uniform location where to store the value
  14175. * @param matrices defines the array of float32 to store
  14176. */
  14177. Engine.prototype.setMatrices = function (uniform, matrices) {
  14178. if (!uniform)
  14179. return;
  14180. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14181. };
  14182. /**
  14183. * Set the value of an uniform to a matrix
  14184. * @param uniform defines the webGL uniform location where to store the value
  14185. * @param matrix defines the matrix to store
  14186. */
  14187. Engine.prototype.setMatrix = function (uniform, matrix) {
  14188. if (!uniform)
  14189. return;
  14190. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14191. };
  14192. /**
  14193. * Set the value of an uniform to a matrix (3x3)
  14194. * @param uniform defines the webGL uniform location where to store the value
  14195. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14196. */
  14197. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14198. if (!uniform)
  14199. return;
  14200. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14201. };
  14202. /**
  14203. * Set the value of an uniform to a matrix (2x2)
  14204. * @param uniform defines the webGL uniform location where to store the value
  14205. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14206. */
  14207. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14208. if (!uniform)
  14209. return;
  14210. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14211. };
  14212. /**
  14213. * Set the value of an uniform to a number (int)
  14214. * @param uniform defines the webGL uniform location where to store the value
  14215. * @param value defines the int number to store
  14216. */
  14217. Engine.prototype.setInt = function (uniform, value) {
  14218. if (!uniform)
  14219. return;
  14220. this._gl.uniform1i(uniform, value);
  14221. };
  14222. /**
  14223. * Set the value of an uniform to a number (float)
  14224. * @param uniform defines the webGL uniform location where to store the value
  14225. * @param value defines the float number to store
  14226. */
  14227. Engine.prototype.setFloat = function (uniform, value) {
  14228. if (!uniform)
  14229. return;
  14230. this._gl.uniform1f(uniform, value);
  14231. };
  14232. /**
  14233. * Set the value of an uniform to a vec2
  14234. * @param uniform defines the webGL uniform location where to store the value
  14235. * @param x defines the 1st component of the value
  14236. * @param y defines the 2nd component of the value
  14237. */
  14238. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14239. if (!uniform)
  14240. return;
  14241. this._gl.uniform2f(uniform, x, y);
  14242. };
  14243. /**
  14244. * Set the value of an uniform to a vec3
  14245. * @param uniform defines the webGL uniform location where to store the value
  14246. * @param x defines the 1st component of the value
  14247. * @param y defines the 2nd component of the value
  14248. * @param z defines the 3rd component of the value
  14249. */
  14250. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14251. if (!uniform)
  14252. return;
  14253. this._gl.uniform3f(uniform, x, y, z);
  14254. };
  14255. /**
  14256. * Set the value of an uniform to a boolean
  14257. * @param uniform defines the webGL uniform location where to store the value
  14258. * @param bool defines the boolean to store
  14259. */
  14260. Engine.prototype.setBool = function (uniform, bool) {
  14261. if (!uniform)
  14262. return;
  14263. this._gl.uniform1i(uniform, bool);
  14264. };
  14265. /**
  14266. * Set the value of an uniform to a vec4
  14267. * @param uniform defines the webGL uniform location where to store the value
  14268. * @param x defines the 1st component of the value
  14269. * @param y defines the 2nd component of the value
  14270. * @param z defines the 3rd component of the value
  14271. * @param w defines the 4th component of the value
  14272. */
  14273. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14274. if (!uniform)
  14275. return;
  14276. this._gl.uniform4f(uniform, x, y, z, w);
  14277. };
  14278. /**
  14279. * Set the value of an uniform to a Color3
  14280. * @param uniform defines the webGL uniform location where to store the value
  14281. * @param color3 defines the color to store
  14282. */
  14283. Engine.prototype.setColor3 = function (uniform, color3) {
  14284. if (!uniform)
  14285. return;
  14286. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14287. };
  14288. /**
  14289. * Set the value of an uniform to a Color3 and an alpha value
  14290. * @param uniform defines the webGL uniform location where to store the value
  14291. * @param color3 defines the color to store
  14292. * @param alpha defines the alpha component to store
  14293. */
  14294. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14295. if (!uniform)
  14296. return;
  14297. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14298. };
  14299. /**
  14300. * Sets a Color4 on a uniform variable
  14301. * @param uniform defines the uniform location
  14302. * @param color4 defines the value to be set
  14303. */
  14304. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14305. if (!uniform)
  14306. return;
  14307. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14308. };
  14309. // States
  14310. /**
  14311. * Set various states to the webGL context
  14312. * @param culling defines backface culling state
  14313. * @param zOffset defines the value to apply to zOffset (0 by default)
  14314. * @param force defines if states must be applied even if cache is up to date
  14315. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14316. */
  14317. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14318. if (zOffset === void 0) { zOffset = 0; }
  14319. if (reverseSide === void 0) { reverseSide = false; }
  14320. // Culling
  14321. if (this._depthCullingState.cull !== culling || force) {
  14322. this._depthCullingState.cull = culling;
  14323. }
  14324. // Cull face
  14325. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14326. if (this._depthCullingState.cullFace !== cullFace || force) {
  14327. this._depthCullingState.cullFace = cullFace;
  14328. }
  14329. // Z offset
  14330. this.setZOffset(zOffset);
  14331. // Front face
  14332. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14333. if (this._depthCullingState.frontFace !== frontFace || force) {
  14334. this._depthCullingState.frontFace = frontFace;
  14335. }
  14336. };
  14337. /**
  14338. * Set the z offset to apply to current rendering
  14339. * @param value defines the offset to apply
  14340. */
  14341. Engine.prototype.setZOffset = function (value) {
  14342. this._depthCullingState.zOffset = value;
  14343. };
  14344. /**
  14345. * Gets the current value of the zOffset
  14346. * @returns the current zOffset state
  14347. */
  14348. Engine.prototype.getZOffset = function () {
  14349. return this._depthCullingState.zOffset;
  14350. };
  14351. /**
  14352. * Enable or disable depth buffering
  14353. * @param enable defines the state to set
  14354. */
  14355. Engine.prototype.setDepthBuffer = function (enable) {
  14356. this._depthCullingState.depthTest = enable;
  14357. };
  14358. /**
  14359. * Gets a boolean indicating if depth writing is enabled
  14360. * @returns the current depth writing state
  14361. */
  14362. Engine.prototype.getDepthWrite = function () {
  14363. return this._depthCullingState.depthMask;
  14364. };
  14365. /**
  14366. * Enable or disable depth writing
  14367. * @param enable defines the state to set
  14368. */
  14369. Engine.prototype.setDepthWrite = function (enable) {
  14370. this._depthCullingState.depthMask = enable;
  14371. };
  14372. /**
  14373. * Enable or disable color writing
  14374. * @param enable defines the state to set
  14375. */
  14376. Engine.prototype.setColorWrite = function (enable) {
  14377. this._gl.colorMask(enable, enable, enable, enable);
  14378. this._colorWrite = enable;
  14379. };
  14380. /**
  14381. * Gets a boolean indicating if color writing is enabled
  14382. * @returns the current color writing state
  14383. */
  14384. Engine.prototype.getColorWrite = function () {
  14385. return this._colorWrite;
  14386. };
  14387. /**
  14388. * Sets alpha constants used by some alpha blending modes
  14389. * @param r defines the red component
  14390. * @param g defines the green component
  14391. * @param b defines the blue component
  14392. * @param a defines the alpha component
  14393. */
  14394. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14395. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14396. };
  14397. /**
  14398. * Sets the current alpha mode
  14399. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14400. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14401. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14402. */
  14403. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14404. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14405. if (this._alphaMode === mode) {
  14406. return;
  14407. }
  14408. switch (mode) {
  14409. case Engine.ALPHA_DISABLE:
  14410. this._alphaState.alphaBlend = false;
  14411. break;
  14412. case Engine.ALPHA_PREMULTIPLIED:
  14413. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14414. this._alphaState.alphaBlend = true;
  14415. break;
  14416. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14417. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14418. this._alphaState.alphaBlend = true;
  14419. break;
  14420. case Engine.ALPHA_COMBINE:
  14421. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14422. this._alphaState.alphaBlend = true;
  14423. break;
  14424. case Engine.ALPHA_ONEONE:
  14425. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14426. this._alphaState.alphaBlend = true;
  14427. break;
  14428. case Engine.ALPHA_ADD:
  14429. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14430. this._alphaState.alphaBlend = true;
  14431. break;
  14432. case Engine.ALPHA_SUBTRACT:
  14433. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14434. this._alphaState.alphaBlend = true;
  14435. break;
  14436. case Engine.ALPHA_MULTIPLY:
  14437. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14438. this._alphaState.alphaBlend = true;
  14439. break;
  14440. case Engine.ALPHA_MAXIMIZED:
  14441. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14442. this._alphaState.alphaBlend = true;
  14443. break;
  14444. case Engine.ALPHA_INTERPOLATE:
  14445. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14446. this._alphaState.alphaBlend = true;
  14447. break;
  14448. case Engine.ALPHA_SCREENMODE:
  14449. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14450. this._alphaState.alphaBlend = true;
  14451. break;
  14452. }
  14453. if (!noDepthWriteChange) {
  14454. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14455. }
  14456. this._alphaMode = mode;
  14457. };
  14458. /**
  14459. * Gets the current alpha mode
  14460. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14461. * @returns the current alpha mode
  14462. */
  14463. Engine.prototype.getAlphaMode = function () {
  14464. return this._alphaMode;
  14465. };
  14466. // Textures
  14467. /**
  14468. * Force the entire cache to be cleared
  14469. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14470. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14471. */
  14472. Engine.prototype.wipeCaches = function (bruteForce) {
  14473. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14474. return;
  14475. }
  14476. this._currentEffect = null;
  14477. if (bruteForce) {
  14478. this.resetTextureCache();
  14479. this._currentProgram = null;
  14480. this._stencilState.reset();
  14481. this._depthCullingState.reset();
  14482. this.setDepthFunctionToLessOrEqual();
  14483. this._alphaState.reset();
  14484. }
  14485. this._resetVertexBufferBinding();
  14486. this._cachedIndexBuffer = null;
  14487. this._cachedEffectForVertexBuffers = null;
  14488. this._unbindVertexArrayObject();
  14489. this.bindIndexBuffer(null);
  14490. };
  14491. /**
  14492. * Set the compressed texture format to use, based on the formats you have, and the formats
  14493. * supported by the hardware / browser.
  14494. *
  14495. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14496. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14497. * to API arguments needed to compressed textures. This puts the burden on the container
  14498. * generator to house the arcane code for determining these for current & future formats.
  14499. *
  14500. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14501. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14502. *
  14503. * Note: The result of this call is not taken into account when a texture is base64.
  14504. *
  14505. * @param formatsAvailable defines the list of those format families you have created
  14506. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14507. *
  14508. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14509. * @returns The extension selected.
  14510. */
  14511. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14512. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14513. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14514. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14515. return this._textureFormatInUse = this._texturesSupported[i];
  14516. }
  14517. }
  14518. }
  14519. // actively set format to nothing, to allow this to be called more than once
  14520. // and possibly fail the 2nd time
  14521. this._textureFormatInUse = null;
  14522. return null;
  14523. };
  14524. /** @hidden */
  14525. Engine.prototype._createTexture = function () {
  14526. var texture = this._gl.createTexture();
  14527. if (!texture) {
  14528. throw new Error("Unable to create texture");
  14529. }
  14530. return texture;
  14531. };
  14532. /**
  14533. * Usually called from BABYLON.Texture.ts.
  14534. * Passed information to create a WebGLTexture
  14535. * @param urlArg defines a value which contains one of the following:
  14536. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14537. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14538. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14539. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14540. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14541. * @param scene needed for loading to the correct scene
  14542. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14543. * @param onLoad optional callback to be called upon successful completion
  14544. * @param onError optional callback to be called upon failure
  14545. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14546. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14547. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14548. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14549. */
  14550. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14551. var _this = this;
  14552. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14553. if (onLoad === void 0) { onLoad = null; }
  14554. if (onError === void 0) { onError = null; }
  14555. if (buffer === void 0) { buffer = null; }
  14556. if (fallback === void 0) { fallback = null; }
  14557. if (format === void 0) { format = null; }
  14558. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14559. var fromData = url.substr(0, 5) === "data:";
  14560. var fromBlob = url.substr(0, 5) === "blob:";
  14561. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14562. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14563. // establish the file extension, if possible
  14564. var lastDot = url.lastIndexOf('.');
  14565. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14566. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14567. var isTGA = (extension.indexOf(".tga") === 0);
  14568. // determine if a ktx file should be substituted
  14569. var isKTX = false;
  14570. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14571. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14572. isKTX = true;
  14573. }
  14574. if (scene) {
  14575. scene._addPendingData(texture);
  14576. }
  14577. texture.url = url;
  14578. texture.generateMipMaps = !noMipmap;
  14579. texture.samplingMode = samplingMode;
  14580. texture.invertY = invertY;
  14581. if (!this._doNotHandleContextLost) {
  14582. // Keep a link to the buffer only if we plan to handle context lost
  14583. texture._buffer = buffer;
  14584. }
  14585. var onLoadObserver = null;
  14586. if (onLoad && !fallback) {
  14587. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14588. }
  14589. if (!fallback)
  14590. this._internalTexturesCache.push(texture);
  14591. var onerror = function (message, exception) {
  14592. if (scene) {
  14593. scene._removePendingData(texture);
  14594. }
  14595. if (onLoadObserver) {
  14596. texture.onLoadedObservable.remove(onLoadObserver);
  14597. }
  14598. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14599. if (isKTX) {
  14600. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14601. }
  14602. else if (BABYLON.Tools.UseFallbackTexture) {
  14603. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14604. }
  14605. if (onError) {
  14606. onError(message || "Unknown error", exception);
  14607. }
  14608. };
  14609. var callback = null;
  14610. // processing for non-image formats
  14611. if (isKTX || isTGA || isDDS) {
  14612. if (isKTX) {
  14613. callback = function (data) {
  14614. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14615. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14616. ktx.uploadLevels(_this._gl, !noMipmap);
  14617. return false;
  14618. }, samplingMode);
  14619. };
  14620. }
  14621. else if (isTGA) {
  14622. callback = function (arrayBuffer) {
  14623. var data = new Uint8Array(arrayBuffer);
  14624. var header = BABYLON.TGATools.GetTGAHeader(data);
  14625. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14626. BABYLON.TGATools.UploadContent(_this._gl, data);
  14627. return false;
  14628. }, samplingMode);
  14629. };
  14630. }
  14631. else if (isDDS) {
  14632. callback = function (data) {
  14633. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14634. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14635. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14636. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14637. return false;
  14638. }, samplingMode);
  14639. };
  14640. }
  14641. if (!buffer) {
  14642. this._loadFile(url, function (data) {
  14643. if (callback) {
  14644. callback(data);
  14645. }
  14646. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14647. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14648. });
  14649. }
  14650. else {
  14651. if (callback) {
  14652. callback(buffer);
  14653. }
  14654. }
  14655. // image format processing
  14656. }
  14657. else {
  14658. var onload = function (img) {
  14659. if (fromBlob && !_this._doNotHandleContextLost) {
  14660. // We need to store the image if we need to rebuild the texture
  14661. // in case of a webgl context lost
  14662. texture._buffer = img;
  14663. }
  14664. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14665. var gl = _this._gl;
  14666. var isPot = (img.width === potWidth && img.height === potHeight);
  14667. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14668. if (isPot) {
  14669. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14670. return false;
  14671. }
  14672. // Using shaders to rescale because canvas.drawImage is lossy
  14673. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14674. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14675. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14676. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14677. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14678. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14679. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14680. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14681. _this._releaseTexture(source);
  14682. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14683. continuationCallback();
  14684. });
  14685. return true;
  14686. }, samplingMode);
  14687. };
  14688. if (!fromData || isBase64) {
  14689. if (buffer instanceof HTMLImageElement) {
  14690. onload(buffer);
  14691. }
  14692. else {
  14693. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14694. }
  14695. }
  14696. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14697. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14698. }
  14699. else {
  14700. onload(buffer);
  14701. }
  14702. }
  14703. return texture;
  14704. };
  14705. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14706. var _this = this;
  14707. var rtt = this.createRenderTargetTexture({
  14708. width: destination.width,
  14709. height: destination.height,
  14710. }, {
  14711. generateMipMaps: false,
  14712. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14713. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14714. generateDepthBuffer: false,
  14715. generateStencilBuffer: false
  14716. });
  14717. if (!this._rescalePostProcess) {
  14718. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14719. }
  14720. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14721. _this._rescalePostProcess.onApply = function (effect) {
  14722. effect._bindTexture("textureSampler", source);
  14723. };
  14724. var hostingScene = scene;
  14725. if (!hostingScene) {
  14726. hostingScene = _this.scenes[_this.scenes.length - 1];
  14727. }
  14728. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14729. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14730. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14731. _this.unBindFramebuffer(rtt);
  14732. _this._releaseTexture(rtt);
  14733. if (onComplete) {
  14734. onComplete();
  14735. }
  14736. });
  14737. };
  14738. /**
  14739. * Update a raw texture
  14740. * @param texture defines the texture to update
  14741. * @param data defines the data to store in the texture
  14742. * @param format defines the format of the data
  14743. * @param invertY defines if data must be stored with Y axis inverted
  14744. * @param compression defines the compression used (null by default)
  14745. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14746. */
  14747. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14748. if (compression === void 0) { compression = null; }
  14749. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14750. if (!texture) {
  14751. return;
  14752. }
  14753. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14754. var internalFormat = this._getInternalFormat(format);
  14755. var textureType = this._getWebGLTextureType(type);
  14756. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14757. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14758. if (!this._doNotHandleContextLost) {
  14759. texture._bufferView = data;
  14760. texture.format = format;
  14761. texture.type = type;
  14762. texture.invertY = invertY;
  14763. texture._compression = compression;
  14764. }
  14765. if (texture.width % 4 !== 0) {
  14766. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14767. }
  14768. if (compression && data) {
  14769. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14770. }
  14771. else {
  14772. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14773. }
  14774. if (texture.generateMipMaps) {
  14775. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14776. }
  14777. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14778. // this.resetTextureCache();
  14779. texture.isReady = true;
  14780. };
  14781. /**
  14782. * Creates a raw texture
  14783. * @param data defines the data to store in the texture
  14784. * @param width defines the width of the texture
  14785. * @param height defines the height of the texture
  14786. * @param format defines the format of the data
  14787. * @param generateMipMaps defines if the engine should generate the mip levels
  14788. * @param invertY defines if data must be stored with Y axis inverted
  14789. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14790. * @param compression defines the compression used (null by default)
  14791. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14792. * @returns the raw texture inside an InternalTexture
  14793. */
  14794. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14795. if (compression === void 0) { compression = null; }
  14796. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14797. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14798. texture.baseWidth = width;
  14799. texture.baseHeight = height;
  14800. texture.width = width;
  14801. texture.height = height;
  14802. texture.format = format;
  14803. texture.generateMipMaps = generateMipMaps;
  14804. texture.samplingMode = samplingMode;
  14805. texture.invertY = invertY;
  14806. texture._compression = compression;
  14807. texture.type = type;
  14808. if (!this._doNotHandleContextLost) {
  14809. texture._bufferView = data;
  14810. }
  14811. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14812. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14813. // Filters
  14814. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14815. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14816. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14817. if (generateMipMaps) {
  14818. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14819. }
  14820. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14821. this._internalTexturesCache.push(texture);
  14822. return texture;
  14823. };
  14824. /**
  14825. * Creates a dynamic texture
  14826. * @param width defines the width of the texture
  14827. * @param height defines the height of the texture
  14828. * @param generateMipMaps defines if the engine should generate the mip levels
  14829. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14830. * @returns the dynamic texture inside an InternalTexture
  14831. */
  14832. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14833. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14834. texture.baseWidth = width;
  14835. texture.baseHeight = height;
  14836. if (generateMipMaps) {
  14837. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14838. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14839. }
  14840. // this.resetTextureCache();
  14841. texture.width = width;
  14842. texture.height = height;
  14843. texture.isReady = false;
  14844. texture.generateMipMaps = generateMipMaps;
  14845. texture.samplingMode = samplingMode;
  14846. this.updateTextureSamplingMode(samplingMode, texture);
  14847. this._internalTexturesCache.push(texture);
  14848. return texture;
  14849. };
  14850. /**
  14851. * Update the sampling mode of a given texture
  14852. * @param samplingMode defines the required sampling mode
  14853. * @param texture defines the texture to update
  14854. */
  14855. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14856. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14857. if (texture.isCube) {
  14858. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14859. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14860. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14861. }
  14862. else if (texture.is3D) {
  14863. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14864. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14865. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14866. }
  14867. else {
  14868. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14869. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14870. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14871. }
  14872. texture.samplingMode = samplingMode;
  14873. };
  14874. /**
  14875. * Update the content of a dynamic texture
  14876. * @param texture defines the texture to update
  14877. * @param canvas defines the canvas containing the source
  14878. * @param invertY defines if data must be stored with Y axis inverted
  14879. * @param premulAlpha defines if alpha is stored as premultiplied
  14880. * @param format defines the format of the data
  14881. */
  14882. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14883. if (premulAlpha === void 0) { premulAlpha = false; }
  14884. if (!texture) {
  14885. return;
  14886. }
  14887. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14888. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14889. if (premulAlpha) {
  14890. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14891. }
  14892. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14893. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14894. if (texture.generateMipMaps) {
  14895. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14896. }
  14897. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14898. if (premulAlpha) {
  14899. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14900. }
  14901. texture.isReady = true;
  14902. };
  14903. /**
  14904. * Update a video texture
  14905. * @param texture defines the texture to update
  14906. * @param video defines the video element to use
  14907. * @param invertY defines if data must be stored with Y axis inverted
  14908. */
  14909. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14910. if (!texture || texture._isDisabled) {
  14911. return;
  14912. }
  14913. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14914. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14915. try {
  14916. // Testing video texture support
  14917. if (this._videoTextureSupported === undefined) {
  14918. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14919. if (this._gl.getError() !== 0) {
  14920. this._videoTextureSupported = false;
  14921. }
  14922. else {
  14923. this._videoTextureSupported = true;
  14924. }
  14925. }
  14926. // Copy video through the current working canvas if video texture is not supported
  14927. if (!this._videoTextureSupported) {
  14928. if (!texture._workingCanvas) {
  14929. texture._workingCanvas = document.createElement("canvas");
  14930. var context = texture._workingCanvas.getContext("2d");
  14931. if (!context) {
  14932. throw new Error("Unable to get 2d context");
  14933. }
  14934. texture._workingContext = context;
  14935. texture._workingCanvas.width = texture.width;
  14936. texture._workingCanvas.height = texture.height;
  14937. }
  14938. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14939. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14940. }
  14941. else {
  14942. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14943. }
  14944. if (texture.generateMipMaps) {
  14945. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14946. }
  14947. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14948. // this.resetTextureCache();
  14949. texture.isReady = true;
  14950. }
  14951. catch (ex) {
  14952. // Something unexpected
  14953. // Let's disable the texture
  14954. texture._isDisabled = true;
  14955. }
  14956. };
  14957. /**
  14958. * Updates a depth texture Comparison Mode and Function.
  14959. * If the comparison Function is equal to 0, the mode will be set to none.
  14960. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14961. * @param texture The texture to set the comparison function for
  14962. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14963. */
  14964. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14965. if (this.webGLVersion === 1) {
  14966. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14967. return;
  14968. }
  14969. var gl = this._gl;
  14970. if (texture.isCube) {
  14971. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14972. if (comparisonFunction === 0) {
  14973. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14974. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14975. }
  14976. else {
  14977. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14978. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14979. }
  14980. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14981. }
  14982. else {
  14983. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14984. if (comparisonFunction === 0) {
  14985. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14986. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14987. }
  14988. else {
  14989. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14990. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14991. }
  14992. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14993. }
  14994. texture._comparisonFunction = comparisonFunction;
  14995. };
  14996. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14997. var width = size.width || size;
  14998. var height = size.height || size;
  14999. internalTexture.baseWidth = width;
  15000. internalTexture.baseHeight = height;
  15001. internalTexture.width = width;
  15002. internalTexture.height = height;
  15003. internalTexture.isReady = true;
  15004. internalTexture.samples = 1;
  15005. internalTexture.generateMipMaps = false;
  15006. internalTexture._generateDepthBuffer = true;
  15007. internalTexture._generateStencilBuffer = generateStencil;
  15008. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15009. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15010. internalTexture._comparisonFunction = comparisonFunction;
  15011. var gl = this._gl;
  15012. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15013. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15014. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15015. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15016. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15017. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15018. if (comparisonFunction === 0) {
  15019. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15020. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15021. }
  15022. else {
  15023. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15024. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15025. }
  15026. };
  15027. /**
  15028. * Creates a depth stencil texture.
  15029. * This is only available in WebGL 2 or with the depth texture extension available.
  15030. * @param size The size of face edge in the texture.
  15031. * @param options The options defining the texture.
  15032. * @returns The texture
  15033. */
  15034. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15035. if (options.isCube) {
  15036. var width = size.width || size;
  15037. return this._createDepthStencilCubeTexture(width, options);
  15038. }
  15039. else {
  15040. return this._createDepthStencilTexture(size, options);
  15041. }
  15042. };
  15043. /**
  15044. * Creates a depth stencil texture.
  15045. * This is only available in WebGL 2 or with the depth texture extension available.
  15046. * @param size The size of face edge in the texture.
  15047. * @param options The options defining the texture.
  15048. * @returns The texture
  15049. */
  15050. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15051. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15052. if (!this._caps.depthTextureExtension) {
  15053. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15054. return internalTexture;
  15055. }
  15056. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15057. var gl = this._gl;
  15058. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15059. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15060. if (this.webGLVersion > 1) {
  15061. if (internalOptions.generateStencil) {
  15062. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15063. }
  15064. else {
  15065. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15066. }
  15067. }
  15068. else {
  15069. if (internalOptions.generateStencil) {
  15070. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15071. }
  15072. else {
  15073. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15074. }
  15075. }
  15076. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15077. return internalTexture;
  15078. };
  15079. /**
  15080. * Creates a depth stencil cube texture.
  15081. * This is only available in WebGL 2.
  15082. * @param size The size of face edge in the cube texture.
  15083. * @param options The options defining the cube texture.
  15084. * @returns The cube texture
  15085. */
  15086. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15087. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15088. internalTexture.isCube = true;
  15089. if (this.webGLVersion === 1) {
  15090. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15091. return internalTexture;
  15092. }
  15093. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15094. var gl = this._gl;
  15095. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15096. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15097. // Create the depth/stencil buffer
  15098. for (var face = 0; face < 6; face++) {
  15099. if (internalOptions.generateStencil) {
  15100. 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);
  15101. }
  15102. else {
  15103. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15104. }
  15105. }
  15106. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15107. return internalTexture;
  15108. };
  15109. /**
  15110. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15111. * @param renderTarget The render target to set the frame buffer for
  15112. */
  15113. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15114. // Create the framebuffer
  15115. var internalTexture = renderTarget.getInternalTexture();
  15116. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15117. return;
  15118. }
  15119. var gl = this._gl;
  15120. var depthStencilTexture = renderTarget.depthStencilTexture;
  15121. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15122. if (depthStencilTexture.isCube) {
  15123. if (depthStencilTexture._generateStencilBuffer) {
  15124. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15125. }
  15126. else {
  15127. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15128. }
  15129. }
  15130. else {
  15131. if (depthStencilTexture._generateStencilBuffer) {
  15132. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15133. }
  15134. else {
  15135. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15136. }
  15137. }
  15138. this.bindUnboundFramebuffer(null);
  15139. };
  15140. /**
  15141. * Creates a new render target texture
  15142. * @param size defines the size of the texture
  15143. * @param options defines the options used to create the texture
  15144. * @returns a new render target texture stored in an InternalTexture
  15145. */
  15146. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15147. var fullOptions = new RenderTargetCreationOptions();
  15148. if (options !== undefined && typeof options === "object") {
  15149. fullOptions.generateMipMaps = options.generateMipMaps;
  15150. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15151. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15152. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15153. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15154. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15155. }
  15156. else {
  15157. fullOptions.generateMipMaps = options;
  15158. fullOptions.generateDepthBuffer = true;
  15159. fullOptions.generateStencilBuffer = false;
  15160. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15161. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15162. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15163. }
  15164. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15165. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15166. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15167. }
  15168. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15169. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15170. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15171. }
  15172. var gl = this._gl;
  15173. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15174. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15175. var width = size.width || size;
  15176. var height = size.height || size;
  15177. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15178. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15179. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15180. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15181. }
  15182. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15183. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15184. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15185. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15186. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15187. // Create the framebuffer
  15188. var currentFrameBuffer = this._currentFramebuffer;
  15189. var framebuffer = gl.createFramebuffer();
  15190. this.bindUnboundFramebuffer(framebuffer);
  15191. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15192. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15193. if (fullOptions.generateMipMaps) {
  15194. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15195. }
  15196. // Unbind
  15197. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15198. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15199. this.bindUnboundFramebuffer(currentFrameBuffer);
  15200. texture._framebuffer = framebuffer;
  15201. texture.baseWidth = width;
  15202. texture.baseHeight = height;
  15203. texture.width = width;
  15204. texture.height = height;
  15205. texture.isReady = true;
  15206. texture.samples = 1;
  15207. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15208. texture.samplingMode = fullOptions.samplingMode;
  15209. texture.type = fullOptions.type;
  15210. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15211. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15212. // this.resetTextureCache();
  15213. this._internalTexturesCache.push(texture);
  15214. return texture;
  15215. };
  15216. /**
  15217. * Create a multi render target texture
  15218. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15219. * @param size defines the size of the texture
  15220. * @param options defines the creation options
  15221. * @returns the cube texture as an InternalTexture
  15222. */
  15223. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15224. var generateMipMaps = false;
  15225. var generateDepthBuffer = true;
  15226. var generateStencilBuffer = false;
  15227. var generateDepthTexture = false;
  15228. var textureCount = 1;
  15229. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15230. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15231. var types = new Array();
  15232. var samplingModes = new Array();
  15233. if (options !== undefined) {
  15234. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15235. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15236. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15237. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15238. textureCount = options.textureCount || 1;
  15239. if (options.types) {
  15240. types = options.types;
  15241. }
  15242. if (options.samplingModes) {
  15243. samplingModes = options.samplingModes;
  15244. }
  15245. }
  15246. var gl = this._gl;
  15247. // Create the framebuffer
  15248. var framebuffer = gl.createFramebuffer();
  15249. this.bindUnboundFramebuffer(framebuffer);
  15250. var width = size.width || size;
  15251. var height = size.height || size;
  15252. var textures = [];
  15253. var attachments = [];
  15254. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15255. for (var i = 0; i < textureCount; i++) {
  15256. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15257. var type = types[i] || defaultType;
  15258. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15259. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15260. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15261. }
  15262. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15263. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15264. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15265. }
  15266. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15267. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15268. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15269. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15270. }
  15271. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15272. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15273. textures.push(texture);
  15274. attachments.push(attachment);
  15275. gl.activeTexture(gl["TEXTURE" + i]);
  15276. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15277. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15278. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15279. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15280. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15281. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15282. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15283. if (generateMipMaps) {
  15284. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15285. }
  15286. // Unbind
  15287. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15288. texture._framebuffer = framebuffer;
  15289. texture._depthStencilBuffer = depthStencilBuffer;
  15290. texture.baseWidth = width;
  15291. texture.baseHeight = height;
  15292. texture.width = width;
  15293. texture.height = height;
  15294. texture.isReady = true;
  15295. texture.samples = 1;
  15296. texture.generateMipMaps = generateMipMaps;
  15297. texture.samplingMode = samplingMode;
  15298. texture.type = type;
  15299. texture._generateDepthBuffer = generateDepthBuffer;
  15300. texture._generateStencilBuffer = generateStencilBuffer;
  15301. texture._attachments = attachments;
  15302. this._internalTexturesCache.push(texture);
  15303. }
  15304. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15305. // Depth texture
  15306. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15307. gl.activeTexture(gl.TEXTURE0);
  15308. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15309. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15310. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15311. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15312. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15313. 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);
  15314. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15315. depthTexture._framebuffer = framebuffer;
  15316. depthTexture.baseWidth = width;
  15317. depthTexture.baseHeight = height;
  15318. depthTexture.width = width;
  15319. depthTexture.height = height;
  15320. depthTexture.isReady = true;
  15321. depthTexture.samples = 1;
  15322. depthTexture.generateMipMaps = generateMipMaps;
  15323. depthTexture.samplingMode = gl.NEAREST;
  15324. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15325. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15326. textures.push(depthTexture);
  15327. this._internalTexturesCache.push(depthTexture);
  15328. }
  15329. gl.drawBuffers(attachments);
  15330. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15331. this.bindUnboundFramebuffer(null);
  15332. this.resetTextureCache();
  15333. return textures;
  15334. };
  15335. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15336. if (samples === void 0) { samples = 1; }
  15337. var depthStencilBuffer = null;
  15338. var gl = this._gl;
  15339. // Create the depth/stencil buffer
  15340. if (generateStencilBuffer) {
  15341. depthStencilBuffer = gl.createRenderbuffer();
  15342. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15343. if (samples > 1) {
  15344. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15345. }
  15346. else {
  15347. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15348. }
  15349. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15350. }
  15351. else if (generateDepthBuffer) {
  15352. depthStencilBuffer = gl.createRenderbuffer();
  15353. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15354. if (samples > 1) {
  15355. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15356. }
  15357. else {
  15358. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15359. }
  15360. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15361. }
  15362. return depthStencilBuffer;
  15363. };
  15364. /**
  15365. * Updates the sample count of a render target texture
  15366. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15367. * @param texture defines the texture to update
  15368. * @param samples defines the sample count to set
  15369. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15370. */
  15371. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15372. if (this.webGLVersion < 2 || !texture) {
  15373. return 1;
  15374. }
  15375. if (texture.samples === samples) {
  15376. return samples;
  15377. }
  15378. var gl = this._gl;
  15379. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15380. // Dispose previous render buffers
  15381. if (texture._depthStencilBuffer) {
  15382. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15383. texture._depthStencilBuffer = null;
  15384. }
  15385. if (texture._MSAAFramebuffer) {
  15386. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15387. texture._MSAAFramebuffer = null;
  15388. }
  15389. if (texture._MSAARenderBuffer) {
  15390. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15391. texture._MSAARenderBuffer = null;
  15392. }
  15393. if (samples > 1) {
  15394. var framebuffer = gl.createFramebuffer();
  15395. if (!framebuffer) {
  15396. throw new Error("Unable to create multi sampled framebuffer");
  15397. }
  15398. texture._MSAAFramebuffer = framebuffer;
  15399. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15400. var colorRenderbuffer = gl.createRenderbuffer();
  15401. if (!colorRenderbuffer) {
  15402. throw new Error("Unable to create multi sampled framebuffer");
  15403. }
  15404. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15405. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15406. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15407. texture._MSAARenderBuffer = colorRenderbuffer;
  15408. }
  15409. else {
  15410. this.bindUnboundFramebuffer(texture._framebuffer);
  15411. }
  15412. texture.samples = samples;
  15413. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15414. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15415. this.bindUnboundFramebuffer(null);
  15416. return samples;
  15417. };
  15418. /**
  15419. * Update the sample count for a given multiple render target texture
  15420. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15421. * @param textures defines the textures to update
  15422. * @param samples defines the sample count to set
  15423. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15424. */
  15425. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15426. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15427. return 1;
  15428. }
  15429. if (textures[0].samples === samples) {
  15430. return samples;
  15431. }
  15432. var gl = this._gl;
  15433. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15434. // Dispose previous render buffers
  15435. if (textures[0]._depthStencilBuffer) {
  15436. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15437. textures[0]._depthStencilBuffer = null;
  15438. }
  15439. if (textures[0]._MSAAFramebuffer) {
  15440. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15441. textures[0]._MSAAFramebuffer = null;
  15442. }
  15443. for (var i = 0; i < textures.length; i++) {
  15444. if (textures[i]._MSAARenderBuffer) {
  15445. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15446. textures[i]._MSAARenderBuffer = null;
  15447. }
  15448. }
  15449. if (samples > 1) {
  15450. var framebuffer = gl.createFramebuffer();
  15451. if (!framebuffer) {
  15452. throw new Error("Unable to create multi sampled framebuffer");
  15453. }
  15454. this.bindUnboundFramebuffer(framebuffer);
  15455. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15456. var attachments = [];
  15457. for (var i = 0; i < textures.length; i++) {
  15458. var texture = textures[i];
  15459. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15460. var colorRenderbuffer = gl.createRenderbuffer();
  15461. if (!colorRenderbuffer) {
  15462. throw new Error("Unable to create multi sampled framebuffer");
  15463. }
  15464. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15465. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15466. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15467. texture._MSAAFramebuffer = framebuffer;
  15468. texture._MSAARenderBuffer = colorRenderbuffer;
  15469. texture.samples = samples;
  15470. texture._depthStencilBuffer = depthStencilBuffer;
  15471. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15472. attachments.push(attachment);
  15473. }
  15474. gl.drawBuffers(attachments);
  15475. }
  15476. else {
  15477. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15478. }
  15479. this.bindUnboundFramebuffer(null);
  15480. return samples;
  15481. };
  15482. /** @hidden */
  15483. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15484. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15485. };
  15486. /** @hidden */
  15487. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15488. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15489. };
  15490. /**
  15491. * Creates a new render target cube texture
  15492. * @param size defines the size of the texture
  15493. * @param options defines the options used to create the texture
  15494. * @returns a new render target cube texture stored in an InternalTexture
  15495. */
  15496. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15497. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15498. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15499. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15500. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15501. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15502. }
  15503. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15504. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15505. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15506. }
  15507. var gl = this._gl;
  15508. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15509. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15510. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15511. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15512. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15513. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15514. }
  15515. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15516. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15517. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15518. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15519. for (var face = 0; face < 6; face++) {
  15520. 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);
  15521. }
  15522. // Create the framebuffer
  15523. var framebuffer = gl.createFramebuffer();
  15524. this.bindUnboundFramebuffer(framebuffer);
  15525. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15526. // MipMaps
  15527. if (fullOptions.generateMipMaps) {
  15528. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15529. }
  15530. // Unbind
  15531. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15532. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15533. this.bindUnboundFramebuffer(null);
  15534. texture._framebuffer = framebuffer;
  15535. texture.width = size;
  15536. texture.height = size;
  15537. texture.isReady = true;
  15538. texture.isCube = true;
  15539. texture.samples = 1;
  15540. texture.generateMipMaps = fullOptions.generateMipMaps;
  15541. texture.samplingMode = fullOptions.samplingMode;
  15542. texture.type = fullOptions.type;
  15543. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15544. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15545. this._internalTexturesCache.push(texture);
  15546. return texture;
  15547. };
  15548. /**
  15549. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15550. * @param rootUrl defines the url where the file to load is located
  15551. * @param scene defines the current scene
  15552. * @param scale defines scale to apply to the mip map selection
  15553. * @param offset defines offset to apply to the mip map selection
  15554. * @param onLoad defines an optional callback raised when the texture is loaded
  15555. * @param onError defines an optional callback raised if there is an issue to load the texture
  15556. * @param format defines the format of the data
  15557. * @param forcedExtension defines the extension to use to pick the right loader
  15558. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15559. * @returns the cube texture as an InternalTexture
  15560. */
  15561. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15562. var _this = this;
  15563. if (onLoad === void 0) { onLoad = null; }
  15564. if (onError === void 0) { onError = null; }
  15565. if (forcedExtension === void 0) { forcedExtension = null; }
  15566. if (createPolynomials === void 0) { createPolynomials = true; }
  15567. var callback = function (loadData) {
  15568. if (!loadData) {
  15569. if (onLoad) {
  15570. onLoad(null);
  15571. }
  15572. return;
  15573. }
  15574. var texture = loadData.texture;
  15575. if (!createPolynomials) {
  15576. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15577. }
  15578. else if (loadData.info.sphericalPolynomial) {
  15579. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15580. }
  15581. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15582. texture._lodGenerationScale = scale;
  15583. texture._lodGenerationOffset = offset;
  15584. if (_this._caps.textureLOD) {
  15585. // Do not add extra process if texture lod is supported.
  15586. if (onLoad) {
  15587. onLoad(texture);
  15588. }
  15589. return;
  15590. }
  15591. var mipSlices = 3;
  15592. var gl = _this._gl;
  15593. var width = loadData.width;
  15594. if (!width) {
  15595. return;
  15596. }
  15597. var textures = [];
  15598. for (var i = 0; i < mipSlices; i++) {
  15599. //compute LOD from even spacing in smoothness (matching shader calculation)
  15600. var smoothness = i / (mipSlices - 1);
  15601. var roughness = 1 - smoothness;
  15602. var minLODIndex = offset; // roughness = 0
  15603. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15604. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15605. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15606. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15607. glTextureFromLod.isCube = true;
  15608. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15609. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15610. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15611. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15612. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15613. if (loadData.isDDS) {
  15614. var info = loadData.info;
  15615. var data = loadData.data;
  15616. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15617. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15618. }
  15619. else {
  15620. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15621. }
  15622. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15623. // Wrap in a base texture for easy binding.
  15624. var lodTexture = new BABYLON.BaseTexture(scene);
  15625. lodTexture.isCube = true;
  15626. lodTexture._texture = glTextureFromLod;
  15627. glTextureFromLod.isReady = true;
  15628. textures.push(lodTexture);
  15629. }
  15630. texture._lodTextureHigh = textures[2];
  15631. texture._lodTextureMid = textures[1];
  15632. texture._lodTextureLow = textures[0];
  15633. if (onLoad) {
  15634. onLoad(texture);
  15635. }
  15636. };
  15637. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials);
  15638. };
  15639. /**
  15640. * Creates a cube texture
  15641. * @param rootUrl defines the url where the files to load is located
  15642. * @param scene defines the current scene
  15643. * @param files defines the list of files to load (1 per face)
  15644. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15645. * @param onLoad defines an optional callback raised when the texture is loaded
  15646. * @param onError defines an optional callback raised if there is an issue to load the texture
  15647. * @param format defines the format of the data
  15648. * @param forcedExtension defines the extension to use to pick the right loader
  15649. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15650. * @returns the cube texture as an InternalTexture
  15651. */
  15652. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15653. var _this = this;
  15654. if (onLoad === void 0) { onLoad = null; }
  15655. if (onError === void 0) { onError = null; }
  15656. if (forcedExtension === void 0) { forcedExtension = null; }
  15657. if (createPolynomials === void 0) { createPolynomials = false; }
  15658. var gl = this._gl;
  15659. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15660. texture.isCube = true;
  15661. texture.url = rootUrl;
  15662. texture.generateMipMaps = !noMipmap;
  15663. if (!this._doNotHandleContextLost) {
  15664. texture._extension = forcedExtension;
  15665. texture._files = files;
  15666. }
  15667. var isKTX = false;
  15668. var isDDS = false;
  15669. var lastDot = rootUrl.lastIndexOf('.');
  15670. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15671. if (this._textureFormatInUse) {
  15672. extension = this._textureFormatInUse;
  15673. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15674. isKTX = true;
  15675. }
  15676. else {
  15677. isDDS = (extension === ".dds");
  15678. }
  15679. var onerror = function (request, exception) {
  15680. if (onError && request) {
  15681. onError(request.status + " " + request.statusText, exception);
  15682. }
  15683. };
  15684. if (isKTX) {
  15685. this._loadFile(rootUrl, function (data) {
  15686. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15687. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15688. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15689. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15690. ktx.uploadLevels(_this._gl, !noMipmap);
  15691. _this.setCubeMapTextureParams(gl, loadMipmap);
  15692. texture.width = ktx.pixelWidth;
  15693. texture.height = ktx.pixelHeight;
  15694. texture.isReady = true;
  15695. }, undefined, undefined, true, onerror);
  15696. }
  15697. else if (isDDS) {
  15698. if (files && files.length === 6) {
  15699. this._cascadeLoadFiles(scene, function (imgs) {
  15700. var info;
  15701. var loadMipmap = false;
  15702. var width = 0;
  15703. for (var index = 0; index < imgs.length; index++) {
  15704. var data = imgs[index];
  15705. info = BABYLON.DDSTools.GetDDSInfo(data);
  15706. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15707. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15708. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15709. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15710. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15711. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15712. }
  15713. texture.width = info.width;
  15714. texture.height = info.height;
  15715. texture.type = info.textureType;
  15716. width = info.width;
  15717. }
  15718. _this.setCubeMapTextureParams(gl, loadMipmap);
  15719. texture.isReady = true;
  15720. if (onLoad) {
  15721. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15722. }
  15723. }, files, onError);
  15724. }
  15725. else {
  15726. this._loadFile(rootUrl, function (data) {
  15727. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15728. if (createPolynomials) {
  15729. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15730. }
  15731. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15732. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15733. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15734. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15735. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15736. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15737. }
  15738. _this.setCubeMapTextureParams(gl, loadMipmap);
  15739. texture.width = info.width;
  15740. texture.height = info.height;
  15741. texture.isReady = true;
  15742. texture.type = info.textureType;
  15743. if (onLoad) {
  15744. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15745. }
  15746. }, undefined, undefined, true, onerror);
  15747. }
  15748. }
  15749. else {
  15750. if (!files) {
  15751. throw new Error("Cannot load cubemap because files were not defined");
  15752. }
  15753. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15754. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15755. var height = width;
  15756. _this._prepareWorkingCanvas();
  15757. if (!_this._workingCanvas || !_this._workingContext) {
  15758. return;
  15759. }
  15760. _this._workingCanvas.width = width;
  15761. _this._workingCanvas.height = height;
  15762. var faces = [
  15763. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15764. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15765. ];
  15766. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15767. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15768. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15769. for (var index = 0; index < faces.length; index++) {
  15770. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15771. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15772. }
  15773. if (!noMipmap) {
  15774. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15775. }
  15776. _this.setCubeMapTextureParams(gl, !noMipmap);
  15777. texture.width = width;
  15778. texture.height = height;
  15779. texture.isReady = true;
  15780. if (format) {
  15781. texture.format = format;
  15782. }
  15783. texture.onLoadedObservable.notifyObservers(texture);
  15784. texture.onLoadedObservable.clear();
  15785. if (onLoad) {
  15786. onLoad();
  15787. }
  15788. }, files, onError);
  15789. }
  15790. this._internalTexturesCache.push(texture);
  15791. return texture;
  15792. };
  15793. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15794. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15795. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15796. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15797. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15798. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15799. // this.resetTextureCache();
  15800. };
  15801. /**
  15802. * Update a raw cube texture
  15803. * @param texture defines the texture to udpdate
  15804. * @param data defines the data to store
  15805. * @param format defines the data format
  15806. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15807. * @param invertY defines if data must be stored with Y axis inverted
  15808. * @param compression defines the compression used (null by default)
  15809. * @param level defines which level of the texture to update
  15810. */
  15811. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15812. if (compression === void 0) { compression = null; }
  15813. if (level === void 0) { level = 0; }
  15814. texture._bufferViewArray = data;
  15815. texture.format = format;
  15816. texture.type = type;
  15817. texture.invertY = invertY;
  15818. texture._compression = compression;
  15819. var gl = this._gl;
  15820. var textureType = this._getWebGLTextureType(type);
  15821. var internalFormat = this._getInternalFormat(format);
  15822. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15823. var needConversion = false;
  15824. if (internalFormat === gl.RGB) {
  15825. internalFormat = gl.RGBA;
  15826. needConversion = true;
  15827. }
  15828. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15829. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15830. if (texture.width % 4 !== 0) {
  15831. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15832. }
  15833. // Data are known to be in +X +Y +Z -X -Y -Z
  15834. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15835. var faceData = data[faceIndex];
  15836. if (compression) {
  15837. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15838. }
  15839. else {
  15840. if (needConversion) {
  15841. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15842. }
  15843. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15844. }
  15845. }
  15846. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15847. if (isPot && texture.generateMipMaps && level === 0) {
  15848. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15849. }
  15850. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15851. // this.resetTextureCache();
  15852. texture.isReady = true;
  15853. };
  15854. /**
  15855. * Creates a new raw cube texture
  15856. * @param data defines the array of data to use to create each face
  15857. * @param size defines the size of the textures
  15858. * @param format defines the format of the data
  15859. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15860. * @param generateMipMaps defines if the engine should generate the mip levels
  15861. * @param invertY defines if data must be stored with Y axis inverted
  15862. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15863. * @param compression defines the compression used (null by default)
  15864. * @returns the cube texture as an InternalTexture
  15865. */
  15866. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15867. if (compression === void 0) { compression = null; }
  15868. var gl = this._gl;
  15869. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15870. texture.isCube = true;
  15871. texture.generateMipMaps = generateMipMaps;
  15872. texture.format = format;
  15873. texture.type = type;
  15874. if (!this._doNotHandleContextLost) {
  15875. texture._bufferViewArray = data;
  15876. }
  15877. var textureType = this._getWebGLTextureType(type);
  15878. var internalFormat = this._getInternalFormat(format);
  15879. if (internalFormat === gl.RGB) {
  15880. internalFormat = gl.RGBA;
  15881. }
  15882. var width = size;
  15883. var height = width;
  15884. texture.width = width;
  15885. texture.height = height;
  15886. // Double check on POT to generate Mips.
  15887. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15888. if (!isPot) {
  15889. generateMipMaps = false;
  15890. }
  15891. // Upload data if needed. The texture won't be ready until then.
  15892. if (data) {
  15893. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15894. }
  15895. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15896. // Filters
  15897. if (data && generateMipMaps) {
  15898. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15899. }
  15900. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15901. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15902. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15903. }
  15904. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15906. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15907. }
  15908. else {
  15909. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15910. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15911. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15912. }
  15913. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15914. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15915. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15916. return texture;
  15917. };
  15918. /**
  15919. * Creates a new raw cube texture from a specified url
  15920. * @param url defines the url where the data is located
  15921. * @param scene defines the current scene
  15922. * @param size defines the size of the textures
  15923. * @param format defines the format of the data
  15924. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15925. * @param noMipmap defines if the engine should avoid generating the mip levels
  15926. * @param callback defines a callback used to extract texture data from loaded data
  15927. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15928. * @param onLoad defines a callback called when texture is loaded
  15929. * @param onError defines a callback called if there is an error
  15930. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15931. * @param invertY defines if data must be stored with Y axis inverted
  15932. * @returns the cube texture as an InternalTexture
  15933. */
  15934. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15935. var _this = this;
  15936. if (onLoad === void 0) { onLoad = null; }
  15937. if (onError === void 0) { onError = null; }
  15938. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15939. if (invertY === void 0) { invertY = false; }
  15940. var gl = this._gl;
  15941. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15942. scene._addPendingData(texture);
  15943. texture.url = url;
  15944. this._internalTexturesCache.push(texture);
  15945. var onerror = function (request, exception) {
  15946. scene._removePendingData(texture);
  15947. if (onError && request) {
  15948. onError(request.status + " " + request.statusText, exception);
  15949. }
  15950. };
  15951. var internalCallback = function (data) {
  15952. var width = texture.width;
  15953. var faceDataArrays = callback(data);
  15954. if (!faceDataArrays) {
  15955. return;
  15956. }
  15957. if (mipmapGenerator) {
  15958. var textureType = _this._getWebGLTextureType(type);
  15959. var internalFormat = _this._getInternalFormat(format);
  15960. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15961. var needConversion = false;
  15962. if (internalFormat === gl.RGB) {
  15963. internalFormat = gl.RGBA;
  15964. needConversion = true;
  15965. }
  15966. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15967. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15968. var mipData = mipmapGenerator(faceDataArrays);
  15969. for (var level = 0; level < mipData.length; level++) {
  15970. var mipSize = width >> level;
  15971. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15972. var mipFaceData = mipData[level][faceIndex];
  15973. if (needConversion) {
  15974. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15975. }
  15976. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15977. }
  15978. }
  15979. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15980. }
  15981. else {
  15982. texture.generateMipMaps = !noMipmap;
  15983. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15984. }
  15985. texture.isReady = true;
  15986. // this.resetTextureCache();
  15987. scene._removePendingData(texture);
  15988. if (onLoad) {
  15989. onLoad();
  15990. }
  15991. };
  15992. this._loadFile(url, function (data) {
  15993. internalCallback(data);
  15994. }, undefined, scene.database, true, onerror);
  15995. return texture;
  15996. };
  15997. ;
  15998. /**
  15999. * Update a raw 3D texture
  16000. * @param texture defines the texture to update
  16001. * @param data defines the data to store
  16002. * @param format defines the data format
  16003. * @param invertY defines if data must be stored with Y axis inverted
  16004. * @param compression defines the used compression (can be null)
  16005. */
  16006. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  16007. if (compression === void 0) { compression = null; }
  16008. var internalFormat = this._getInternalFormat(format);
  16009. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16010. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16011. if (!this._doNotHandleContextLost) {
  16012. texture._bufferView = data;
  16013. texture.format = format;
  16014. texture.invertY = invertY;
  16015. texture._compression = compression;
  16016. }
  16017. if (texture.width % 4 !== 0) {
  16018. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16019. }
  16020. if (compression && data) {
  16021. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16022. }
  16023. else {
  16024. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  16025. }
  16026. if (texture.generateMipMaps) {
  16027. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16028. }
  16029. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16030. // this.resetTextureCache();
  16031. texture.isReady = true;
  16032. };
  16033. /**
  16034. * Creates a new raw 3D texture
  16035. * @param data defines the data used to create the texture
  16036. * @param width defines the width of the texture
  16037. * @param height defines the height of the texture
  16038. * @param depth defines the depth of the texture
  16039. * @param format defines the format of the texture
  16040. * @param generateMipMaps defines if the engine must generate mip levels
  16041. * @param invertY defines if data must be stored with Y axis inverted
  16042. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16043. * @param compression defines the compressed used (can be null)
  16044. * @returns a new raw 3D texture (stored in an InternalTexture)
  16045. */
  16046. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  16047. if (compression === void 0) { compression = null; }
  16048. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16049. texture.baseWidth = width;
  16050. texture.baseHeight = height;
  16051. texture.baseDepth = depth;
  16052. texture.width = width;
  16053. texture.height = height;
  16054. texture.depth = depth;
  16055. texture.format = format;
  16056. texture.generateMipMaps = generateMipMaps;
  16057. texture.samplingMode = samplingMode;
  16058. texture.is3D = true;
  16059. if (!this._doNotHandleContextLost) {
  16060. texture._bufferView = data;
  16061. }
  16062. this.updateRawTexture3D(texture, data, format, invertY, compression);
  16063. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16064. // Filters
  16065. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16066. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16067. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16068. if (generateMipMaps) {
  16069. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16070. }
  16071. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16072. this._internalTexturesCache.push(texture);
  16073. return texture;
  16074. };
  16075. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16076. var gl = this._gl;
  16077. if (!gl) {
  16078. return;
  16079. }
  16080. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16081. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16082. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16083. if (!noMipmap && !isCompressed) {
  16084. gl.generateMipmap(gl.TEXTURE_2D);
  16085. }
  16086. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16087. // this.resetTextureCache();
  16088. if (scene) {
  16089. scene._removePendingData(texture);
  16090. }
  16091. texture.onLoadedObservable.notifyObservers(texture);
  16092. texture.onLoadedObservable.clear();
  16093. };
  16094. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16095. var _this = this;
  16096. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16097. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16098. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16099. var gl = this._gl;
  16100. if (!gl) {
  16101. return;
  16102. }
  16103. if (!texture._webGLTexture) {
  16104. // this.resetTextureCache();
  16105. if (scene) {
  16106. scene._removePendingData(texture);
  16107. }
  16108. return;
  16109. }
  16110. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16111. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16112. texture.baseWidth = width;
  16113. texture.baseHeight = height;
  16114. texture.width = potWidth;
  16115. texture.height = potHeight;
  16116. texture.isReady = true;
  16117. if (processFunction(potWidth, potHeight, function () {
  16118. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16119. })) {
  16120. // Returning as texture needs extra async steps
  16121. return;
  16122. }
  16123. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16124. };
  16125. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16126. // Create new RGBA data container.
  16127. var rgbaData;
  16128. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16129. rgbaData = new Float32Array(width * height * 4);
  16130. }
  16131. else {
  16132. rgbaData = new Uint32Array(width * height * 4);
  16133. }
  16134. // Convert each pixel.
  16135. for (var x = 0; x < width; x++) {
  16136. for (var y = 0; y < height; y++) {
  16137. var index = (y * width + x) * 3;
  16138. var newIndex = (y * width + x) * 4;
  16139. // Map Old Value to new value.
  16140. rgbaData[newIndex + 0] = rgbData[index + 0];
  16141. rgbaData[newIndex + 1] = rgbData[index + 1];
  16142. rgbaData[newIndex + 2] = rgbData[index + 2];
  16143. // Add fully opaque alpha channel.
  16144. rgbaData[newIndex + 3] = 1;
  16145. }
  16146. }
  16147. return rgbaData;
  16148. };
  16149. /** @hidden */
  16150. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16151. var gl = this._gl;
  16152. if (texture._framebuffer) {
  16153. gl.deleteFramebuffer(texture._framebuffer);
  16154. texture._framebuffer = null;
  16155. }
  16156. if (texture._depthStencilBuffer) {
  16157. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16158. texture._depthStencilBuffer = null;
  16159. }
  16160. if (texture._MSAAFramebuffer) {
  16161. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16162. texture._MSAAFramebuffer = null;
  16163. }
  16164. if (texture._MSAARenderBuffer) {
  16165. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16166. texture._MSAARenderBuffer = null;
  16167. }
  16168. };
  16169. /** @hidden */
  16170. Engine.prototype._releaseTexture = function (texture) {
  16171. var gl = this._gl;
  16172. this._releaseFramebufferObjects(texture);
  16173. gl.deleteTexture(texture._webGLTexture);
  16174. // Unbind channels
  16175. this.unbindAllTextures();
  16176. var index = this._internalTexturesCache.indexOf(texture);
  16177. if (index !== -1) {
  16178. this._internalTexturesCache.splice(index, 1);
  16179. }
  16180. // Integrated fixed lod samplers.
  16181. if (texture._lodTextureHigh) {
  16182. texture._lodTextureHigh.dispose();
  16183. }
  16184. if (texture._lodTextureMid) {
  16185. texture._lodTextureMid.dispose();
  16186. }
  16187. if (texture._lodTextureLow) {
  16188. texture._lodTextureLow.dispose();
  16189. }
  16190. // Set output texture of post process to null if the texture has been released/disposed
  16191. this.scenes.forEach(function (scene) {
  16192. scene.postProcesses.forEach(function (postProcess) {
  16193. if (postProcess._outputTexture == texture) {
  16194. postProcess._outputTexture = null;
  16195. }
  16196. });
  16197. scene.cameras.forEach(function (camera) {
  16198. camera._postProcesses.forEach(function (postProcess) {
  16199. if (postProcess) {
  16200. if (postProcess._outputTexture == texture) {
  16201. postProcess._outputTexture = null;
  16202. }
  16203. }
  16204. });
  16205. });
  16206. });
  16207. };
  16208. Engine.prototype.setProgram = function (program) {
  16209. if (this._currentProgram !== program) {
  16210. this._gl.useProgram(program);
  16211. this._currentProgram = program;
  16212. }
  16213. };
  16214. /**
  16215. * Binds an effect to the webGL context
  16216. * @param effect defines the effect to bind
  16217. */
  16218. Engine.prototype.bindSamplers = function (effect) {
  16219. this.setProgram(effect.getProgram());
  16220. var samplers = effect.getSamplers();
  16221. for (var index = 0; index < samplers.length; index++) {
  16222. var uniform = effect.getUniform(samplers[index]);
  16223. if (uniform) {
  16224. this._boundUniforms[index] = uniform;
  16225. }
  16226. }
  16227. this._currentEffect = null;
  16228. };
  16229. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16230. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16231. return;
  16232. }
  16233. // Remove
  16234. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16235. // Bind last to it
  16236. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16237. // Bind to dummy
  16238. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16239. };
  16240. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16241. if (!internalTexture) {
  16242. return -1;
  16243. }
  16244. internalTexture._initialSlot = channel;
  16245. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16246. if (channel !== internalTexture._designatedSlot) {
  16247. this._textureCollisions.addCount(1, false);
  16248. }
  16249. }
  16250. else {
  16251. if (channel !== internalTexture._designatedSlot) {
  16252. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16253. return internalTexture._designatedSlot;
  16254. }
  16255. else {
  16256. // No slot for this texture, let's pick a new one (if we find a free slot)
  16257. if (this._nextFreeTextureSlots.length) {
  16258. return this._nextFreeTextureSlots[0];
  16259. }
  16260. // We need to recycle the oldest bound texture, sorry.
  16261. this._textureCollisions.addCount(1, false);
  16262. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16263. }
  16264. }
  16265. }
  16266. return channel;
  16267. };
  16268. Engine.prototype._linkTrackers = function (previous, next) {
  16269. previous.next = next;
  16270. next.previous = previous;
  16271. };
  16272. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16273. var currentSlot = internalTexture._designatedSlot;
  16274. if (currentSlot === -1) {
  16275. return -1;
  16276. }
  16277. internalTexture._designatedSlot = -1;
  16278. if (this.disableTextureBindingOptimization) {
  16279. return -1;
  16280. }
  16281. // Remove from bound list
  16282. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16283. // Free the slot
  16284. this._boundTexturesCache[currentSlot] = null;
  16285. this._nextFreeTextureSlots.push(currentSlot);
  16286. return currentSlot;
  16287. };
  16288. Engine.prototype._activateCurrentTexture = function () {
  16289. if (this._currentTextureChannel !== this._activeChannel) {
  16290. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16291. this._currentTextureChannel = this._activeChannel;
  16292. }
  16293. };
  16294. /** @hidden */
  16295. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16296. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16297. if (force === void 0) { force = false; }
  16298. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16299. this._activeChannel = texture._designatedSlot;
  16300. }
  16301. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16302. var isTextureForRendering = texture && texture._initialSlot > -1;
  16303. if (currentTextureBound !== texture || force) {
  16304. if (currentTextureBound) {
  16305. this._removeDesignatedSlot(currentTextureBound);
  16306. }
  16307. this._activateCurrentTexture();
  16308. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16309. this._boundTexturesCache[this._activeChannel] = texture;
  16310. if (texture) {
  16311. if (!this.disableTextureBindingOptimization) {
  16312. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16313. if (slotIndex > -1) {
  16314. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16315. }
  16316. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16317. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16318. }
  16319. texture._designatedSlot = this._activeChannel;
  16320. }
  16321. }
  16322. else if (forTextureDataUpdate) {
  16323. this._activateCurrentTexture();
  16324. }
  16325. if (isTextureForRendering && !forTextureDataUpdate) {
  16326. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16327. }
  16328. };
  16329. /** @hidden */
  16330. Engine.prototype._bindTexture = function (channel, texture) {
  16331. if (channel < 0) {
  16332. return;
  16333. }
  16334. if (texture) {
  16335. channel = this._getCorrectTextureChannel(channel, texture);
  16336. }
  16337. this._activeChannel = channel;
  16338. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16339. };
  16340. /**
  16341. * Sets a texture to the webGL context from a postprocess
  16342. * @param channel defines the channel to use
  16343. * @param postProcess defines the source postprocess
  16344. */
  16345. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16346. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16347. };
  16348. /**
  16349. * Binds the output of the passed in post process to the texture channel specified
  16350. * @param channel The channel the texture should be bound to
  16351. * @param postProcess The post process which's output should be bound
  16352. */
  16353. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16354. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16355. };
  16356. /**
  16357. * Unbind all textures from the webGL context
  16358. */
  16359. Engine.prototype.unbindAllTextures = function () {
  16360. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16361. this._activeChannel = channel;
  16362. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16363. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16364. if (this.webGLVersion > 1) {
  16365. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16366. }
  16367. }
  16368. };
  16369. /**
  16370. * Sets a texture to the according uniform.
  16371. * @param channel The texture channel
  16372. * @param uniform The uniform to set
  16373. * @param texture The texture to apply
  16374. */
  16375. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16376. if (channel < 0) {
  16377. return;
  16378. }
  16379. if (uniform) {
  16380. this._boundUniforms[channel] = uniform;
  16381. }
  16382. this._setTexture(channel, texture);
  16383. };
  16384. /**
  16385. * Sets a depth stencil texture from a render target to the according uniform.
  16386. * @param channel The texture channel
  16387. * @param uniform The uniform to set
  16388. * @param texture The render target texture containing the depth stencil texture to apply
  16389. */
  16390. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16391. if (channel < 0) {
  16392. return;
  16393. }
  16394. if (uniform) {
  16395. this._boundUniforms[channel] = uniform;
  16396. }
  16397. if (!texture || !texture.depthStencilTexture) {
  16398. this._setTexture(channel, null);
  16399. }
  16400. else {
  16401. this._setTexture(channel, texture, false, true);
  16402. }
  16403. };
  16404. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16405. var uniform = this._boundUniforms[sourceSlot];
  16406. if (uniform._currentState === destination) {
  16407. return;
  16408. }
  16409. this._gl.uniform1i(uniform, destination);
  16410. uniform._currentState = destination;
  16411. };
  16412. Engine.prototype._getTextureWrapMode = function (mode) {
  16413. switch (mode) {
  16414. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16415. return this._gl.REPEAT;
  16416. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16417. return this._gl.CLAMP_TO_EDGE;
  16418. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16419. return this._gl.MIRRORED_REPEAT;
  16420. }
  16421. return this._gl.REPEAT;
  16422. };
  16423. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16424. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16425. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16426. // Not ready?
  16427. if (!texture) {
  16428. if (this._boundTexturesCache[channel] != null) {
  16429. this._activeChannel = channel;
  16430. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16431. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16432. if (this.webGLVersion > 1) {
  16433. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16434. }
  16435. }
  16436. return false;
  16437. }
  16438. // Video
  16439. if (texture.video) {
  16440. this._activeChannel = channel;
  16441. texture.update();
  16442. }
  16443. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16444. texture.delayLoad();
  16445. return false;
  16446. }
  16447. var internalTexture;
  16448. if (depthStencilTexture) {
  16449. internalTexture = texture.depthStencilTexture;
  16450. }
  16451. else if (texture.isReady()) {
  16452. internalTexture = texture.getInternalTexture();
  16453. }
  16454. else if (texture.isCube) {
  16455. internalTexture = this.emptyCubeTexture;
  16456. }
  16457. else if (texture.is3D) {
  16458. internalTexture = this.emptyTexture3D;
  16459. }
  16460. else {
  16461. internalTexture = this.emptyTexture;
  16462. }
  16463. if (!isPartOfTextureArray) {
  16464. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16465. }
  16466. var needToBind = true;
  16467. if (this._boundTexturesCache[channel] === internalTexture) {
  16468. this._moveBoundTextureOnTop(internalTexture);
  16469. if (!isPartOfTextureArray) {
  16470. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16471. }
  16472. needToBind = false;
  16473. }
  16474. this._activeChannel = channel;
  16475. if (internalTexture && internalTexture.is3D) {
  16476. if (needToBind) {
  16477. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16478. }
  16479. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16480. internalTexture._cachedWrapU = texture.wrapU;
  16481. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16482. }
  16483. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16484. internalTexture._cachedWrapV = texture.wrapV;
  16485. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16486. }
  16487. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16488. internalTexture._cachedWrapR = texture.wrapR;
  16489. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16490. }
  16491. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16492. }
  16493. else if (internalTexture && internalTexture.isCube) {
  16494. if (needToBind) {
  16495. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16496. }
  16497. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16498. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16499. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16500. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16501. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16502. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16503. }
  16504. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16505. }
  16506. else {
  16507. if (needToBind) {
  16508. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16509. }
  16510. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16511. internalTexture._cachedWrapU = texture.wrapU;
  16512. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16513. }
  16514. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16515. internalTexture._cachedWrapV = texture.wrapV;
  16516. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16517. }
  16518. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16519. }
  16520. return true;
  16521. };
  16522. /**
  16523. * Sets an array of texture to the webGL context
  16524. * @param channel defines the channel where the texture array must be set
  16525. * @param uniform defines the associated uniform location
  16526. * @param textures defines the array of textures to bind
  16527. */
  16528. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16529. if (channel < 0 || !uniform) {
  16530. return;
  16531. }
  16532. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16533. this._textureUnits = new Int32Array(textures.length);
  16534. }
  16535. for (var i = 0; i < textures.length; i++) {
  16536. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16537. }
  16538. this._gl.uniform1iv(uniform, this._textureUnits);
  16539. for (var index = 0; index < textures.length; index++) {
  16540. this._setTexture(this._textureUnits[index], textures[index], true);
  16541. }
  16542. };
  16543. /** @hidden */
  16544. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16545. var internalTexture = texture.getInternalTexture();
  16546. if (!internalTexture) {
  16547. return;
  16548. }
  16549. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16550. var value = texture.anisotropicFilteringLevel;
  16551. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16552. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16553. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16554. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16555. }
  16556. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16557. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16558. internalTexture._cachedAnisotropicFilteringLevel = value;
  16559. }
  16560. };
  16561. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16562. this._bindTextureDirectly(target, texture, true, true);
  16563. this._gl.texParameterf(target, parameter, value);
  16564. };
  16565. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16566. if (texture) {
  16567. this._bindTextureDirectly(target, texture, true, true);
  16568. }
  16569. this._gl.texParameteri(target, parameter, value);
  16570. };
  16571. /**
  16572. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16573. * @param x defines the x coordinate of the rectangle where pixels must be read
  16574. * @param y defines the y coordinate of the rectangle where pixels must be read
  16575. * @param width defines the width of the rectangle where pixels must be read
  16576. * @param height defines the height of the rectangle where pixels must be read
  16577. * @returns a Uint8Array containing RGBA colors
  16578. */
  16579. Engine.prototype.readPixels = function (x, y, width, height) {
  16580. var data = new Uint8Array(height * width * 4);
  16581. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16582. return data;
  16583. };
  16584. /**
  16585. * Add an externaly attached data from its key.
  16586. * This method call will fail and return false, if such key already exists.
  16587. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16588. * @param key the unique key that identifies the data
  16589. * @param data the data object to associate to the key for this Engine instance
  16590. * @return true if no such key were already present and the data was added successfully, false otherwise
  16591. */
  16592. Engine.prototype.addExternalData = function (key, data) {
  16593. if (!this._externalData) {
  16594. this._externalData = new BABYLON.StringDictionary();
  16595. }
  16596. return this._externalData.add(key, data);
  16597. };
  16598. /**
  16599. * Get an externaly attached data from its key
  16600. * @param key the unique key that identifies the data
  16601. * @return the associated data, if present (can be null), or undefined if not present
  16602. */
  16603. Engine.prototype.getExternalData = function (key) {
  16604. if (!this._externalData) {
  16605. this._externalData = new BABYLON.StringDictionary();
  16606. }
  16607. return this._externalData.get(key);
  16608. };
  16609. /**
  16610. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16611. * @param key the unique key that identifies the data
  16612. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16613. * @return the associated data, can be null if the factory returned null.
  16614. */
  16615. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16616. if (!this._externalData) {
  16617. this._externalData = new BABYLON.StringDictionary();
  16618. }
  16619. return this._externalData.getOrAddWithFactory(key, factory);
  16620. };
  16621. /**
  16622. * Remove an externaly attached data from the Engine instance
  16623. * @param key the unique key that identifies the data
  16624. * @return true if the data was successfully removed, false if it doesn't exist
  16625. */
  16626. Engine.prototype.removeExternalData = function (key) {
  16627. if (!this._externalData) {
  16628. this._externalData = new BABYLON.StringDictionary();
  16629. }
  16630. return this._externalData.remove(key);
  16631. };
  16632. /**
  16633. * Unbind all vertex attributes from the webGL context
  16634. */
  16635. Engine.prototype.unbindAllAttributes = function () {
  16636. if (this._mustWipeVertexAttributes) {
  16637. this._mustWipeVertexAttributes = false;
  16638. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16639. this._gl.disableVertexAttribArray(i);
  16640. this._vertexAttribArraysEnabled[i] = false;
  16641. this._currentBufferPointers[i].active = false;
  16642. }
  16643. return;
  16644. }
  16645. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16646. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16647. continue;
  16648. }
  16649. this._gl.disableVertexAttribArray(i);
  16650. this._vertexAttribArraysEnabled[i] = false;
  16651. this._currentBufferPointers[i].active = false;
  16652. }
  16653. };
  16654. /**
  16655. * 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
  16656. */
  16657. Engine.prototype.releaseEffects = function () {
  16658. for (var name in this._compiledEffects) {
  16659. this._deleteProgram(this._compiledEffects[name]._program);
  16660. }
  16661. this._compiledEffects = {};
  16662. };
  16663. /**
  16664. * Dispose and release all associated resources
  16665. */
  16666. Engine.prototype.dispose = function () {
  16667. this.hideLoadingUI();
  16668. this.stopRenderLoop();
  16669. // Release postProcesses
  16670. while (this.postProcesses.length) {
  16671. this.postProcesses[0].dispose();
  16672. }
  16673. // Empty texture
  16674. if (this._emptyTexture) {
  16675. this._releaseTexture(this._emptyTexture);
  16676. this._emptyTexture = null;
  16677. }
  16678. if (this._emptyCubeTexture) {
  16679. this._releaseTexture(this._emptyCubeTexture);
  16680. this._emptyCubeTexture = null;
  16681. }
  16682. // Rescale PP
  16683. if (this._rescalePostProcess) {
  16684. this._rescalePostProcess.dispose();
  16685. }
  16686. // Release scenes
  16687. while (this.scenes.length) {
  16688. this.scenes[0].dispose();
  16689. }
  16690. // Release audio engine
  16691. if (Engine.audioEngine) {
  16692. Engine.audioEngine.dispose();
  16693. }
  16694. // Release effects
  16695. this.releaseEffects();
  16696. // Unbind
  16697. this.unbindAllAttributes();
  16698. this._boundUniforms = [];
  16699. if (this._dummyFramebuffer) {
  16700. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16701. }
  16702. //WebVR
  16703. this.disableVR();
  16704. // Events
  16705. if (BABYLON.Tools.IsWindowObjectExist()) {
  16706. window.removeEventListener("blur", this._onBlur);
  16707. window.removeEventListener("focus", this._onFocus);
  16708. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16709. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16710. if (this._renderingCanvas) {
  16711. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16712. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16713. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16714. if (!this._doNotHandleContextLost) {
  16715. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16716. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16717. }
  16718. }
  16719. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16720. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16721. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16722. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16723. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16724. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16725. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16726. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16727. if (this._onVrDisplayConnect) {
  16728. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16729. if (this._onVrDisplayDisconnect) {
  16730. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16731. }
  16732. if (this._onVrDisplayPresentChange) {
  16733. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16734. }
  16735. this._onVrDisplayConnect = null;
  16736. this._onVrDisplayDisconnect = null;
  16737. }
  16738. }
  16739. // Remove from Instances
  16740. var index = Engine.Instances.indexOf(this);
  16741. if (index >= 0) {
  16742. Engine.Instances.splice(index, 1);
  16743. }
  16744. this._workingCanvas = null;
  16745. this._workingContext = null;
  16746. this._currentBufferPointers = [];
  16747. this._renderingCanvas = null;
  16748. this._currentProgram = null;
  16749. this._bindedRenderFunction = null;
  16750. this.onResizeObservable.clear();
  16751. this.onCanvasBlurObservable.clear();
  16752. this.onCanvasFocusObservable.clear();
  16753. this.onCanvasPointerOutObservable.clear();
  16754. this.onBeginFrameObservable.clear();
  16755. this.onEndFrameObservable.clear();
  16756. BABYLON.Effect.ResetCache();
  16757. // Abort active requests
  16758. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16759. var request = _a[_i];
  16760. request.abort();
  16761. }
  16762. };
  16763. // Loading screen
  16764. /**
  16765. * Display the loading screen
  16766. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16767. */
  16768. Engine.prototype.displayLoadingUI = function () {
  16769. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16770. return;
  16771. }
  16772. var loadingScreen = this.loadingScreen;
  16773. if (loadingScreen) {
  16774. loadingScreen.displayLoadingUI();
  16775. }
  16776. };
  16777. /**
  16778. * Hide the loading screen
  16779. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16780. */
  16781. Engine.prototype.hideLoadingUI = function () {
  16782. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16783. return;
  16784. }
  16785. var loadingScreen = this.loadingScreen;
  16786. if (loadingScreen) {
  16787. loadingScreen.hideLoadingUI();
  16788. }
  16789. };
  16790. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16791. /**
  16792. * Gets the current loading screen object
  16793. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16794. */
  16795. get: function () {
  16796. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16797. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16798. return this._loadingScreen;
  16799. },
  16800. /**
  16801. * Sets the current loading screen object
  16802. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16803. */
  16804. set: function (loadingScreen) {
  16805. this._loadingScreen = loadingScreen;
  16806. },
  16807. enumerable: true,
  16808. configurable: true
  16809. });
  16810. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16811. /**
  16812. * Sets the current loading screen text
  16813. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16814. */
  16815. set: function (text) {
  16816. this.loadingScreen.loadingUIText = text;
  16817. },
  16818. enumerable: true,
  16819. configurable: true
  16820. });
  16821. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16822. /**
  16823. * Sets the current loading screen background color
  16824. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16825. */
  16826. set: function (color) {
  16827. this.loadingScreen.loadingUIBackgroundColor = color;
  16828. },
  16829. enumerable: true,
  16830. configurable: true
  16831. });
  16832. /**
  16833. * Attach a new callback raised when context lost event is fired
  16834. * @param callback defines the callback to call
  16835. */
  16836. Engine.prototype.attachContextLostEvent = function (callback) {
  16837. if (this._renderingCanvas) {
  16838. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16839. }
  16840. };
  16841. /**
  16842. * Attach a new callback raised when context restored event is fired
  16843. * @param callback defines the callback to call
  16844. */
  16845. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16846. if (this._renderingCanvas) {
  16847. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16848. }
  16849. };
  16850. /**
  16851. * Gets the source code of the vertex shader associated with a specific webGL program
  16852. * @param program defines the program to use
  16853. * @returns a string containing the source code of the vertex shader associated with the program
  16854. */
  16855. Engine.prototype.getVertexShaderSource = function (program) {
  16856. var shaders = this._gl.getAttachedShaders(program);
  16857. if (!shaders) {
  16858. return null;
  16859. }
  16860. return this._gl.getShaderSource(shaders[0]);
  16861. };
  16862. /**
  16863. * Gets the source code of the fragment shader associated with a specific webGL program
  16864. * @param program defines the program to use
  16865. * @returns a string containing the source code of the fragment shader associated with the program
  16866. */
  16867. Engine.prototype.getFragmentShaderSource = function (program) {
  16868. var shaders = this._gl.getAttachedShaders(program);
  16869. if (!shaders) {
  16870. return null;
  16871. }
  16872. return this._gl.getShaderSource(shaders[1]);
  16873. };
  16874. /**
  16875. * Get the current error code of the webGL context
  16876. * @returns the error code
  16877. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16878. */
  16879. Engine.prototype.getError = function () {
  16880. return this._gl.getError();
  16881. };
  16882. // FPS
  16883. /**
  16884. * Gets the current framerate
  16885. * @returns a number representing the framerate
  16886. */
  16887. Engine.prototype.getFps = function () {
  16888. return this._fps;
  16889. };
  16890. /**
  16891. * Gets the time spent between current and previous frame
  16892. * @returns a number representing the delta time in ms
  16893. */
  16894. Engine.prototype.getDeltaTime = function () {
  16895. return this._deltaTime;
  16896. };
  16897. Engine.prototype._measureFps = function () {
  16898. this._performanceMonitor.sampleFrame();
  16899. this._fps = this._performanceMonitor.averageFPS;
  16900. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16901. };
  16902. /** @hidden */
  16903. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16904. if (faceIndex === void 0) { faceIndex = -1; }
  16905. var gl = this._gl;
  16906. if (!this._dummyFramebuffer) {
  16907. var dummy = gl.createFramebuffer();
  16908. if (!dummy) {
  16909. throw new Error("Unable to create dummy framebuffer");
  16910. }
  16911. this._dummyFramebuffer = dummy;
  16912. }
  16913. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16914. if (faceIndex > -1) {
  16915. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16916. }
  16917. else {
  16918. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16919. }
  16920. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16921. var buffer;
  16922. switch (readType) {
  16923. case gl.UNSIGNED_BYTE:
  16924. buffer = new Uint8Array(4 * width * height);
  16925. readType = gl.UNSIGNED_BYTE;
  16926. break;
  16927. default:
  16928. buffer = new Float32Array(4 * width * height);
  16929. readType = gl.FLOAT;
  16930. break;
  16931. }
  16932. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16933. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16934. return buffer;
  16935. };
  16936. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16937. if (this._webGLVersion > 1) {
  16938. return this._caps.colorBufferFloat;
  16939. }
  16940. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16941. };
  16942. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16943. if (this._webGLVersion > 1) {
  16944. return this._caps.colorBufferFloat;
  16945. }
  16946. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16947. };
  16948. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16949. Engine.prototype._canRenderToFramebuffer = function (type) {
  16950. var gl = this._gl;
  16951. //clear existing errors
  16952. while (gl.getError() !== gl.NO_ERROR) { }
  16953. var successful = true;
  16954. var texture = gl.createTexture();
  16955. gl.bindTexture(gl.TEXTURE_2D, texture);
  16956. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16957. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16958. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16959. var fb = gl.createFramebuffer();
  16960. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16961. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16962. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16963. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16964. successful = successful && (gl.getError() === gl.NO_ERROR);
  16965. //try render by clearing frame buffer's color buffer
  16966. if (successful) {
  16967. gl.clear(gl.COLOR_BUFFER_BIT);
  16968. successful = successful && (gl.getError() === gl.NO_ERROR);
  16969. }
  16970. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16971. if (successful) {
  16972. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16973. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16974. var readFormat = gl.RGBA;
  16975. var readType = gl.UNSIGNED_BYTE;
  16976. var buffer = new Uint8Array(4);
  16977. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16978. successful = successful && (gl.getError() === gl.NO_ERROR);
  16979. }
  16980. //clean up
  16981. gl.deleteTexture(texture);
  16982. gl.deleteFramebuffer(fb);
  16983. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16984. //clear accumulated errors
  16985. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16986. return successful;
  16987. };
  16988. /** @hidden */
  16989. Engine.prototype._getWebGLTextureType = function (type) {
  16990. if (type === Engine.TEXTURETYPE_FLOAT) {
  16991. return this._gl.FLOAT;
  16992. }
  16993. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16994. // Add Half Float Constant.
  16995. return this._gl.HALF_FLOAT_OES;
  16996. }
  16997. return this._gl.UNSIGNED_BYTE;
  16998. };
  16999. ;
  17000. Engine.prototype._getInternalFormat = function (format) {
  17001. var internalFormat = this._gl.RGBA;
  17002. switch (format) {
  17003. case Engine.TEXTUREFORMAT_ALPHA:
  17004. internalFormat = this._gl.ALPHA;
  17005. break;
  17006. case Engine.TEXTUREFORMAT_LUMINANCE:
  17007. internalFormat = this._gl.LUMINANCE;
  17008. break;
  17009. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17010. internalFormat = this._gl.LUMINANCE_ALPHA;
  17011. break;
  17012. case Engine.TEXTUREFORMAT_RGB:
  17013. case Engine.TEXTUREFORMAT_RGB32F:
  17014. internalFormat = this._gl.RGB;
  17015. break;
  17016. case Engine.TEXTUREFORMAT_RGBA:
  17017. case Engine.TEXTUREFORMAT_RGBA32F:
  17018. internalFormat = this._gl.RGBA;
  17019. break;
  17020. case Engine.TEXTUREFORMAT_R32F:
  17021. internalFormat = this._gl.RED;
  17022. break;
  17023. case Engine.TEXTUREFORMAT_RG32F:
  17024. internalFormat = this._gl.RG;
  17025. break;
  17026. }
  17027. return internalFormat;
  17028. };
  17029. /** @hidden */
  17030. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17031. if (this._webGLVersion === 1) {
  17032. if (format) {
  17033. switch (format) {
  17034. case Engine.TEXTUREFORMAT_LUMINANCE:
  17035. return this._gl.LUMINANCE;
  17036. }
  17037. }
  17038. return this._gl.RGBA;
  17039. }
  17040. if (type === Engine.TEXTURETYPE_FLOAT) {
  17041. if (format) {
  17042. switch (format) {
  17043. case Engine.TEXTUREFORMAT_R32F:
  17044. return this._gl.R32F;
  17045. case Engine.TEXTUREFORMAT_RG32F:
  17046. return this._gl.RG32F;
  17047. case Engine.TEXTUREFORMAT_RGB32F:
  17048. return this._gl.RGB32F;
  17049. }
  17050. }
  17051. return this._gl.RGBA32F;
  17052. }
  17053. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17054. return this._gl.RGBA16F;
  17055. }
  17056. if (format) {
  17057. switch (format) {
  17058. case Engine.TEXTUREFORMAT_LUMINANCE:
  17059. return this._gl.LUMINANCE;
  17060. case Engine.TEXTUREFORMAT_RGB:
  17061. return this._gl.RGB;
  17062. }
  17063. }
  17064. return this._gl.RGBA;
  17065. };
  17066. ;
  17067. /** @hidden */
  17068. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17069. if (type === Engine.TEXTURETYPE_FLOAT) {
  17070. return this._gl.RGBA32F;
  17071. }
  17072. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17073. return this._gl.RGBA16F;
  17074. }
  17075. return this._gl.RGBA8;
  17076. };
  17077. ;
  17078. /**
  17079. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17080. * @return the new query
  17081. */
  17082. Engine.prototype.createQuery = function () {
  17083. return this._gl.createQuery();
  17084. };
  17085. /**
  17086. * Delete and release a webGL query
  17087. * @param query defines the query to delete
  17088. * @return the current engine
  17089. */
  17090. Engine.prototype.deleteQuery = function (query) {
  17091. this._gl.deleteQuery(query);
  17092. return this;
  17093. };
  17094. /**
  17095. * Check if a given query has resolved and got its value
  17096. * @param query defines the query to check
  17097. * @returns true if the query got its value
  17098. */
  17099. Engine.prototype.isQueryResultAvailable = function (query) {
  17100. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17101. };
  17102. /**
  17103. * Gets the value of a given query
  17104. * @param query defines the query to check
  17105. * @returns the value of the query
  17106. */
  17107. Engine.prototype.getQueryResult = function (query) {
  17108. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17109. };
  17110. /**
  17111. * Initiates an occlusion query
  17112. * @param algorithmType defines the algorithm to use
  17113. * @param query defines the query to use
  17114. * @returns the current engine
  17115. * @see http://doc.babylonjs.com/features/occlusionquery
  17116. */
  17117. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17118. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17119. this._gl.beginQuery(glAlgorithm, query);
  17120. return this;
  17121. };
  17122. /**
  17123. * Ends an occlusion query
  17124. * @see http://doc.babylonjs.com/features/occlusionquery
  17125. * @param algorithmType defines the algorithm to use
  17126. * @returns the current engine
  17127. */
  17128. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17129. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17130. this._gl.endQuery(glAlgorithm);
  17131. return this;
  17132. };
  17133. /* Time queries */
  17134. Engine.prototype._createTimeQuery = function () {
  17135. var timerQuery = this._caps.timerQuery;
  17136. if (timerQuery.createQueryEXT) {
  17137. return timerQuery.createQueryEXT();
  17138. }
  17139. return this.createQuery();
  17140. };
  17141. Engine.prototype._deleteTimeQuery = function (query) {
  17142. var timerQuery = this._caps.timerQuery;
  17143. if (timerQuery.deleteQueryEXT) {
  17144. timerQuery.deleteQueryEXT(query);
  17145. return;
  17146. }
  17147. this.deleteQuery(query);
  17148. };
  17149. Engine.prototype._getTimeQueryResult = function (query) {
  17150. var timerQuery = this._caps.timerQuery;
  17151. if (timerQuery.getQueryObjectEXT) {
  17152. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17153. }
  17154. return this.getQueryResult(query);
  17155. };
  17156. Engine.prototype._getTimeQueryAvailability = function (query) {
  17157. var timerQuery = this._caps.timerQuery;
  17158. if (timerQuery.getQueryObjectEXT) {
  17159. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17160. }
  17161. return this.isQueryResultAvailable(query);
  17162. };
  17163. /**
  17164. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17165. * Please note that only one query can be issued at a time
  17166. * @returns a time token used to track the time span
  17167. */
  17168. Engine.prototype.startTimeQuery = function () {
  17169. var timerQuery = this._caps.timerQuery;
  17170. if (!timerQuery) {
  17171. return null;
  17172. }
  17173. var token = new BABYLON._TimeToken();
  17174. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17175. if (this._caps.canUseTimestampForTimerQuery) {
  17176. token._startTimeQuery = this._createTimeQuery();
  17177. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17178. }
  17179. else {
  17180. if (this._currentNonTimestampToken) {
  17181. return this._currentNonTimestampToken;
  17182. }
  17183. token._timeElapsedQuery = this._createTimeQuery();
  17184. if (timerQuery.beginQueryEXT) {
  17185. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17186. }
  17187. else {
  17188. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17189. }
  17190. this._currentNonTimestampToken = token;
  17191. }
  17192. return token;
  17193. };
  17194. /**
  17195. * Ends a time query
  17196. * @param token defines the token used to measure the time span
  17197. * @returns the time spent (in ns)
  17198. */
  17199. Engine.prototype.endTimeQuery = function (token) {
  17200. var timerQuery = this._caps.timerQuery;
  17201. if (!timerQuery || !token) {
  17202. return -1;
  17203. }
  17204. if (this._caps.canUseTimestampForTimerQuery) {
  17205. if (!token._startTimeQuery) {
  17206. return -1;
  17207. }
  17208. if (!token._endTimeQuery) {
  17209. token._endTimeQuery = this._createTimeQuery();
  17210. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17211. }
  17212. }
  17213. else if (!token._timeElapsedQueryEnded) {
  17214. if (!token._timeElapsedQuery) {
  17215. return -1;
  17216. }
  17217. if (timerQuery.endQueryEXT) {
  17218. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17219. }
  17220. else {
  17221. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17222. }
  17223. token._timeElapsedQueryEnded = true;
  17224. }
  17225. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17226. var available = false;
  17227. if (token._endTimeQuery) {
  17228. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17229. }
  17230. else if (token._timeElapsedQuery) {
  17231. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17232. }
  17233. if (available && !disjoint) {
  17234. var result = 0;
  17235. if (this._caps.canUseTimestampForTimerQuery) {
  17236. if (!token._startTimeQuery || !token._endTimeQuery) {
  17237. return -1;
  17238. }
  17239. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17240. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17241. result = timeEnd - timeStart;
  17242. this._deleteTimeQuery(token._startTimeQuery);
  17243. this._deleteTimeQuery(token._endTimeQuery);
  17244. token._startTimeQuery = null;
  17245. token._endTimeQuery = null;
  17246. }
  17247. else {
  17248. if (!token._timeElapsedQuery) {
  17249. return -1;
  17250. }
  17251. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17252. this._deleteTimeQuery(token._timeElapsedQuery);
  17253. token._timeElapsedQuery = null;
  17254. token._timeElapsedQueryEnded = false;
  17255. this._currentNonTimestampToken = null;
  17256. }
  17257. return result;
  17258. }
  17259. return -1;
  17260. };
  17261. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17262. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17263. };
  17264. // Transform feedback
  17265. /**
  17266. * Creates a webGL transform feedback object
  17267. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17268. * @returns the webGL transform feedback object
  17269. */
  17270. Engine.prototype.createTransformFeedback = function () {
  17271. return this._gl.createTransformFeedback();
  17272. };
  17273. /**
  17274. * Delete a webGL transform feedback object
  17275. * @param value defines the webGL transform feedback object to delete
  17276. */
  17277. Engine.prototype.deleteTransformFeedback = function (value) {
  17278. this._gl.deleteTransformFeedback(value);
  17279. };
  17280. /**
  17281. * Bind a webGL transform feedback object to the webgl context
  17282. * @param value defines the webGL transform feedback object to bind
  17283. */
  17284. Engine.prototype.bindTransformFeedback = function (value) {
  17285. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17286. };
  17287. /**
  17288. * Begins a transform feedback operation
  17289. * @param usePoints defines if points or triangles must be used
  17290. */
  17291. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17292. if (usePoints === void 0) { usePoints = true; }
  17293. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17294. };
  17295. /**
  17296. * Ends a transform feedback operation
  17297. */
  17298. Engine.prototype.endTransformFeedback = function () {
  17299. this._gl.endTransformFeedback();
  17300. };
  17301. /**
  17302. * Specify the varyings to use with transform feedback
  17303. * @param program defines the associated webGL program
  17304. * @param value defines the list of strings representing the varying names
  17305. */
  17306. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17307. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17308. };
  17309. /**
  17310. * Bind a webGL buffer for a transform feedback operation
  17311. * @param value defines the webGL buffer to bind
  17312. */
  17313. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17314. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17315. };
  17316. /** @hidden */
  17317. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17318. var _this = this;
  17319. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17320. this._activeRequests.push(request);
  17321. request.onCompleteObservable.add(function (request) {
  17322. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17323. });
  17324. return request;
  17325. };
  17326. /** @hidden */
  17327. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17328. var _this = this;
  17329. return new Promise(function (resolve, reject) {
  17330. _this._loadFile(url, function (data) {
  17331. resolve(data);
  17332. }, undefined, database, useArrayBuffer, function (request, exception) {
  17333. reject(exception);
  17334. });
  17335. });
  17336. };
  17337. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17338. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17339. var onload = function (data) {
  17340. loadedFiles[index] = data;
  17341. loadedFiles._internalCount++;
  17342. if (loadedFiles._internalCount === 6) {
  17343. onfinish(loadedFiles);
  17344. }
  17345. };
  17346. var onerror = function (request, exception) {
  17347. if (onErrorCallBack && request) {
  17348. onErrorCallBack(request.status + " " + request.statusText, exception);
  17349. }
  17350. };
  17351. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17352. };
  17353. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17354. if (onError === void 0) { onError = null; }
  17355. var loadedFiles = [];
  17356. loadedFiles._internalCount = 0;
  17357. for (var index = 0; index < 6; index++) {
  17358. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17359. }
  17360. };
  17361. // Statics
  17362. /**
  17363. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17364. * @returns true if the engine can be created
  17365. * @ignorenaming
  17366. */
  17367. Engine.isSupported = function () {
  17368. try {
  17369. var tempcanvas = document.createElement("canvas");
  17370. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17371. return gl != null && !!window.WebGLRenderingContext;
  17372. }
  17373. catch (e) {
  17374. return false;
  17375. }
  17376. };
  17377. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17378. Engine.ExceptionList = [
  17379. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17380. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17381. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17382. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17383. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17384. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17385. ];
  17386. /** Gets the list of created engines */
  17387. Engine.Instances = new Array();
  17388. // Const statics
  17389. Engine._ALPHA_DISABLE = 0;
  17390. Engine._ALPHA_ADD = 1;
  17391. Engine._ALPHA_COMBINE = 2;
  17392. Engine._ALPHA_SUBTRACT = 3;
  17393. Engine._ALPHA_MULTIPLY = 4;
  17394. Engine._ALPHA_MAXIMIZED = 5;
  17395. Engine._ALPHA_ONEONE = 6;
  17396. Engine._ALPHA_PREMULTIPLIED = 7;
  17397. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17398. Engine._ALPHA_INTERPOLATE = 9;
  17399. Engine._ALPHA_SCREENMODE = 10;
  17400. Engine._DELAYLOADSTATE_NONE = 0;
  17401. Engine._DELAYLOADSTATE_LOADED = 1;
  17402. Engine._DELAYLOADSTATE_LOADING = 2;
  17403. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17404. Engine._TEXTUREFORMAT_ALPHA = 0;
  17405. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17406. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17407. Engine._TEXTUREFORMAT_RGB = 4;
  17408. Engine._TEXTUREFORMAT_RGBA = 5;
  17409. Engine._TEXTUREFORMAT_R32F = 6;
  17410. Engine._TEXTUREFORMAT_RG32F = 7;
  17411. Engine._TEXTUREFORMAT_RGB32F = 8;
  17412. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17413. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17414. Engine._TEXTURETYPE_FLOAT = 1;
  17415. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17416. // Depht or Stencil test Constants.
  17417. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17418. 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.
  17419. 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.
  17420. 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.
  17421. 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.
  17422. 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.
  17423. 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.
  17424. 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.
  17425. // Stencil Actions Constants.
  17426. Engine._KEEP = 0x1E00;
  17427. Engine._REPLACE = 0x1E01;
  17428. Engine._INCR = 0x1E02;
  17429. Engine._DECR = 0x1E03;
  17430. Engine._INVERT = 0x150A;
  17431. Engine._INCR_WRAP = 0x8507;
  17432. Engine._DECR_WRAP = 0x8508;
  17433. // Texture rescaling mode
  17434. Engine._SCALEMODE_FLOOR = 1;
  17435. Engine._SCALEMODE_NEAREST = 2;
  17436. Engine._SCALEMODE_CEILING = 3;
  17437. // Updatable statics so stick with vars here
  17438. /**
  17439. * Gets or sets the epsilon value used by collision engine
  17440. */
  17441. Engine.CollisionsEpsilon = 0.001;
  17442. /**
  17443. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17444. */
  17445. Engine.CodeRepository = "src/";
  17446. /**
  17447. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17448. */
  17449. Engine.ShadersRepository = "src/Shaders/";
  17450. return Engine;
  17451. }());
  17452. BABYLON.Engine = Engine;
  17453. })(BABYLON || (BABYLON = {}));
  17454. //# sourceMappingURL=babylon.engine.js.map
  17455. var BABYLON;
  17456. (function (BABYLON) {
  17457. /**
  17458. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17459. */
  17460. var Node = /** @class */ (function () {
  17461. /**
  17462. * Creates a new Node
  17463. * @param {string} name - the name and id to be given to this node
  17464. * @param {BABYLON.Scene} the scene this node will be added to
  17465. */
  17466. function Node(name, scene) {
  17467. if (scene === void 0) { scene = null; }
  17468. /**
  17469. * Gets or sets a string used to store user defined state for the node
  17470. */
  17471. this.state = "";
  17472. /**
  17473. * Gets or sets an object used to store user defined information for the node
  17474. */
  17475. this.metadata = null;
  17476. /**
  17477. * Gets or sets a boolean used to define if the node must be serialized
  17478. */
  17479. this.doNotSerialize = false;
  17480. /** @hidden */
  17481. this._isDisposed = false;
  17482. /**
  17483. * Gets a list of Animations associated with the node
  17484. */
  17485. this.animations = new Array();
  17486. this._ranges = {};
  17487. this._isEnabled = true;
  17488. this._isReady = true;
  17489. /** @hidden */
  17490. this._currentRenderId = -1;
  17491. this._parentRenderId = -1;
  17492. this._childRenderId = -1;
  17493. this._animationPropertiesOverride = null;
  17494. /**
  17495. * An event triggered when the mesh is disposed
  17496. */
  17497. this.onDisposeObservable = new BABYLON.Observable();
  17498. // Behaviors
  17499. this._behaviors = new Array();
  17500. this.name = name;
  17501. this.id = name;
  17502. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17503. this.uniqueId = this._scene.getUniqueId();
  17504. this._initCache();
  17505. }
  17506. /**
  17507. * Gets a boolean indicating if the node has been disposed
  17508. * @returns true if the node was disposed
  17509. */
  17510. Node.prototype.isDisposed = function () {
  17511. return this._isDisposed;
  17512. };
  17513. Object.defineProperty(Node.prototype, "parent", {
  17514. get: function () {
  17515. return this._parentNode;
  17516. },
  17517. /**
  17518. * Gets or sets the parent of the node
  17519. */
  17520. set: function (parent) {
  17521. if (this._parentNode === parent) {
  17522. return;
  17523. }
  17524. // Remove self from list of children of parent
  17525. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17526. var index = this._parentNode._children.indexOf(this);
  17527. if (index !== -1) {
  17528. this._parentNode._children.splice(index, 1);
  17529. }
  17530. }
  17531. // Store new parent
  17532. this._parentNode = parent;
  17533. // Add as child to new parent
  17534. if (this._parentNode) {
  17535. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17536. this._parentNode._children = new Array();
  17537. }
  17538. this._parentNode._children.push(this);
  17539. }
  17540. },
  17541. enumerable: true,
  17542. configurable: true
  17543. });
  17544. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17545. /**
  17546. * Gets or sets the animation properties override
  17547. */
  17548. get: function () {
  17549. if (!this._animationPropertiesOverride) {
  17550. return this._scene.animationPropertiesOverride;
  17551. }
  17552. return this._animationPropertiesOverride;
  17553. },
  17554. set: function (value) {
  17555. this._animationPropertiesOverride = value;
  17556. },
  17557. enumerable: true,
  17558. configurable: true
  17559. });
  17560. /**
  17561. * Gets a string idenfifying the name of the class
  17562. * @returns "Node" string
  17563. */
  17564. Node.prototype.getClassName = function () {
  17565. return "Node";
  17566. };
  17567. Object.defineProperty(Node.prototype, "onDispose", {
  17568. /**
  17569. * Sets a callback that will be raised when the node will be disposed
  17570. */
  17571. set: function (callback) {
  17572. if (this._onDisposeObserver) {
  17573. this.onDisposeObservable.remove(this._onDisposeObserver);
  17574. }
  17575. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17576. },
  17577. enumerable: true,
  17578. configurable: true
  17579. });
  17580. /**
  17581. * Gets the scene of the node
  17582. * @returns a {BABYLON.Scene}
  17583. */
  17584. Node.prototype.getScene = function () {
  17585. return this._scene;
  17586. };
  17587. /**
  17588. * Gets the engine of the node
  17589. * @returns a {BABYLON.Engine}
  17590. */
  17591. Node.prototype.getEngine = function () {
  17592. return this._scene.getEngine();
  17593. };
  17594. /**
  17595. * Attach a behavior to the node
  17596. * @see http://doc.babylonjs.com/features/behaviour
  17597. * @param behavior defines the behavior to attach
  17598. * @returns the current Node
  17599. */
  17600. Node.prototype.addBehavior = function (behavior) {
  17601. var _this = this;
  17602. var index = this._behaviors.indexOf(behavior);
  17603. if (index !== -1) {
  17604. return this;
  17605. }
  17606. behavior.init();
  17607. if (this._scene.isLoading) {
  17608. // We defer the attach when the scene will be loaded
  17609. this._scene.onDataLoadedObservable.addOnce(function () {
  17610. behavior.attach(_this);
  17611. });
  17612. }
  17613. else {
  17614. behavior.attach(this);
  17615. }
  17616. this._behaviors.push(behavior);
  17617. return this;
  17618. };
  17619. /**
  17620. * Remove an attached behavior
  17621. * @see http://doc.babylonjs.com/features/behaviour
  17622. * @param behavior defines the behavior to attach
  17623. * @returns the current Node
  17624. */
  17625. Node.prototype.removeBehavior = function (behavior) {
  17626. var index = this._behaviors.indexOf(behavior);
  17627. if (index === -1) {
  17628. return this;
  17629. }
  17630. this._behaviors[index].detach();
  17631. this._behaviors.splice(index, 1);
  17632. return this;
  17633. };
  17634. Object.defineProperty(Node.prototype, "behaviors", {
  17635. /**
  17636. * Gets the list of attached behaviors
  17637. * @see http://doc.babylonjs.com/features/behaviour
  17638. */
  17639. get: function () {
  17640. return this._behaviors;
  17641. },
  17642. enumerable: true,
  17643. configurable: true
  17644. });
  17645. /**
  17646. * Gets an attached behavior by name
  17647. * @param name defines the name of the behavior to look for
  17648. * @see http://doc.babylonjs.com/features/behaviour
  17649. * @returns null if behavior was not found else the requested behavior
  17650. */
  17651. Node.prototype.getBehaviorByName = function (name) {
  17652. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17653. var behavior = _a[_i];
  17654. if (behavior.name === name) {
  17655. return behavior;
  17656. }
  17657. }
  17658. return null;
  17659. };
  17660. /**
  17661. * Returns the world matrix of the node
  17662. * @returns a matrix containing the node's world matrix
  17663. */
  17664. Node.prototype.getWorldMatrix = function () {
  17665. return BABYLON.Matrix.Identity();
  17666. };
  17667. /** @hidden */
  17668. Node.prototype._getWorldMatrixDeterminant = function () {
  17669. return 1;
  17670. };
  17671. // override it in derived class if you add new variables to the cache
  17672. // and call the parent class method
  17673. /** @hidden */
  17674. Node.prototype._initCache = function () {
  17675. this._cache = {};
  17676. this._cache.parent = undefined;
  17677. };
  17678. /** @hidden */
  17679. Node.prototype.updateCache = function (force) {
  17680. if (!force && this.isSynchronized())
  17681. return;
  17682. this._cache.parent = this.parent;
  17683. this._updateCache();
  17684. };
  17685. // override it in derived class if you add new variables to the cache
  17686. // and call the parent class method if !ignoreParentClass
  17687. /** @hidden */
  17688. Node.prototype._updateCache = function (ignoreParentClass) {
  17689. };
  17690. // override it in derived class if you add new variables to the cache
  17691. /** @hidden */
  17692. Node.prototype._isSynchronized = function () {
  17693. return true;
  17694. };
  17695. /** @hidden */
  17696. Node.prototype._markSyncedWithParent = function () {
  17697. if (this.parent) {
  17698. this._parentRenderId = this.parent._childRenderId;
  17699. }
  17700. };
  17701. /** @hidden */
  17702. Node.prototype.isSynchronizedWithParent = function () {
  17703. if (!this.parent) {
  17704. return true;
  17705. }
  17706. if (this._parentRenderId !== this.parent._childRenderId) {
  17707. return false;
  17708. }
  17709. return this.parent.isSynchronized();
  17710. };
  17711. /** @hidden */
  17712. Node.prototype.isSynchronized = function (updateCache) {
  17713. var check = this.hasNewParent();
  17714. check = check || !this.isSynchronizedWithParent();
  17715. check = check || !this._isSynchronized();
  17716. if (updateCache)
  17717. this.updateCache(true);
  17718. return !check;
  17719. };
  17720. /** @hidden */
  17721. Node.prototype.hasNewParent = function (update) {
  17722. if (this._cache.parent === this.parent)
  17723. return false;
  17724. if (update)
  17725. this._cache.parent = this.parent;
  17726. return true;
  17727. };
  17728. /**
  17729. * Is this node ready to be used/rendered
  17730. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17731. * @return true if the node is ready
  17732. */
  17733. Node.prototype.isReady = function (completeCheck) {
  17734. if (completeCheck === void 0) { completeCheck = false; }
  17735. return this._isReady;
  17736. };
  17737. /**
  17738. * Is this node enabled?
  17739. * 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
  17740. * @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
  17741. * @return whether this node (and its parent) is enabled
  17742. */
  17743. Node.prototype.isEnabled = function (checkAncestors) {
  17744. if (checkAncestors === void 0) { checkAncestors = true; }
  17745. if (checkAncestors === false) {
  17746. return this._isEnabled;
  17747. }
  17748. if (this._isEnabled === false) {
  17749. return false;
  17750. }
  17751. if (this.parent !== undefined && this.parent !== null) {
  17752. return this.parent.isEnabled(checkAncestors);
  17753. }
  17754. return true;
  17755. };
  17756. /**
  17757. * Set the enabled state of this node
  17758. * @param value defines the new enabled state
  17759. */
  17760. Node.prototype.setEnabled = function (value) {
  17761. this._isEnabled = value;
  17762. };
  17763. /**
  17764. * Is this node a descendant of the given node?
  17765. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17766. * @param ancestor defines the parent node to inspect
  17767. * @returns a boolean indicating if this node is a descendant of the given node
  17768. */
  17769. Node.prototype.isDescendantOf = function (ancestor) {
  17770. if (this.parent) {
  17771. if (this.parent === ancestor) {
  17772. return true;
  17773. }
  17774. return this.parent.isDescendantOf(ancestor);
  17775. }
  17776. return false;
  17777. };
  17778. /** @hidden */
  17779. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17780. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17781. if (!this._children) {
  17782. return;
  17783. }
  17784. for (var index = 0; index < this._children.length; index++) {
  17785. var item = this._children[index];
  17786. if (!predicate || predicate(item)) {
  17787. results.push(item);
  17788. }
  17789. if (!directDescendantsOnly) {
  17790. item._getDescendants(results, false, predicate);
  17791. }
  17792. }
  17793. };
  17794. /**
  17795. * Will return all nodes that have this node as ascendant
  17796. * @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
  17797. * @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
  17798. * @return all children nodes of all types
  17799. */
  17800. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17801. var results = new Array();
  17802. this._getDescendants(results, directDescendantsOnly, predicate);
  17803. return results;
  17804. };
  17805. /**
  17806. * Get all child-meshes of this node
  17807. * @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
  17808. * @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
  17809. * @returns an array of {BABYLON.AbstractMesh}
  17810. */
  17811. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17812. var results = [];
  17813. this._getDescendants(results, directDescendantsOnly, function (node) {
  17814. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17815. });
  17816. return results;
  17817. };
  17818. /**
  17819. * Get all child-transformNodes of this node
  17820. * @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
  17821. * @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
  17822. * @returns an array of {BABYLON.TransformNode}
  17823. */
  17824. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17825. var results = [];
  17826. this._getDescendants(results, directDescendantsOnly, function (node) {
  17827. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17828. });
  17829. return results;
  17830. };
  17831. /**
  17832. * Get all direct children of this node
  17833. * @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
  17834. * @returns an array of {BABYLON.Node}
  17835. */
  17836. Node.prototype.getChildren = function (predicate) {
  17837. return this.getDescendants(true, predicate);
  17838. };
  17839. /** @hidden */
  17840. Node.prototype._setReady = function (state) {
  17841. if (state === this._isReady) {
  17842. return;
  17843. }
  17844. if (!state) {
  17845. this._isReady = false;
  17846. return;
  17847. }
  17848. if (this.onReady) {
  17849. this.onReady(this);
  17850. }
  17851. this._isReady = true;
  17852. };
  17853. /**
  17854. * Get an animation by name
  17855. * @param name defines the name of the animation to look for
  17856. * @returns null if not found else the requested animation
  17857. */
  17858. Node.prototype.getAnimationByName = function (name) {
  17859. for (var i = 0; i < this.animations.length; i++) {
  17860. var animation = this.animations[i];
  17861. if (animation.name === name) {
  17862. return animation;
  17863. }
  17864. }
  17865. return null;
  17866. };
  17867. /**
  17868. * Creates an animation range for this node
  17869. * @param name defines the name of the range
  17870. * @param from defines the starting key
  17871. * @param to defines the end key
  17872. */
  17873. Node.prototype.createAnimationRange = function (name, from, to) {
  17874. // check name not already in use
  17875. if (!this._ranges[name]) {
  17876. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17877. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17878. if (this.animations[i]) {
  17879. this.animations[i].createRange(name, from, to);
  17880. }
  17881. }
  17882. }
  17883. };
  17884. /**
  17885. * Delete a specific animation range
  17886. * @param name defines the name of the range to delete
  17887. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17888. */
  17889. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17890. if (deleteFrames === void 0) { deleteFrames = true; }
  17891. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17892. if (this.animations[i]) {
  17893. this.animations[i].deleteRange(name, deleteFrames);
  17894. }
  17895. }
  17896. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17897. };
  17898. /**
  17899. * Get an animation range by name
  17900. * @param name defines the name of the animation range to look for
  17901. * @returns null if not found else the requested animation range
  17902. */
  17903. Node.prototype.getAnimationRange = function (name) {
  17904. return this._ranges[name];
  17905. };
  17906. /**
  17907. * Will start the animation sequence
  17908. * @param name defines the range frames for animation sequence
  17909. * @param loop defines if the animation should loop (false by default)
  17910. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17911. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17912. * @returns the object created for this animation. If range does not exist, it will return null
  17913. */
  17914. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17915. var range = this.getAnimationRange(name);
  17916. if (!range) {
  17917. return null;
  17918. }
  17919. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17920. };
  17921. /**
  17922. * Serialize animation ranges into a JSON compatible object
  17923. * @returns serialization object
  17924. */
  17925. Node.prototype.serializeAnimationRanges = function () {
  17926. var serializationRanges = [];
  17927. for (var name in this._ranges) {
  17928. var localRange = this._ranges[name];
  17929. if (!localRange) {
  17930. continue;
  17931. }
  17932. var range = {};
  17933. range.name = name;
  17934. range.from = localRange.from;
  17935. range.to = localRange.to;
  17936. serializationRanges.push(range);
  17937. }
  17938. return serializationRanges;
  17939. };
  17940. /**
  17941. * Computes the world matrix of the node
  17942. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17943. * @returns the world matrix
  17944. */
  17945. Node.prototype.computeWorldMatrix = function (force) {
  17946. return BABYLON.Matrix.Identity();
  17947. };
  17948. /**
  17949. * Releases resources associated with this node.
  17950. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17951. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17952. */
  17953. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17954. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17955. if (!doNotRecurse) {
  17956. var nodes = this.getDescendants(true);
  17957. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17958. var node = nodes_1[_i];
  17959. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17960. }
  17961. }
  17962. else {
  17963. var transformNodes = this.getChildTransformNodes(true);
  17964. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17965. var transformNode = transformNodes_1[_a];
  17966. transformNode.parent = null;
  17967. transformNode.computeWorldMatrix(true);
  17968. }
  17969. }
  17970. this.parent = null;
  17971. // Callback
  17972. this.onDisposeObservable.notifyObservers(this);
  17973. this.onDisposeObservable.clear();
  17974. // Behaviors
  17975. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17976. var behavior = _c[_b];
  17977. behavior.detach();
  17978. }
  17979. this._behaviors = [];
  17980. this._isDisposed = true;
  17981. };
  17982. /**
  17983. * Parse animation range data from a serialization object and store them into a given node
  17984. * @param node defines where to store the animation ranges
  17985. * @param parsedNode defines the serialization object to read data from
  17986. * @param scene defines the hosting scene
  17987. */
  17988. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17989. if (parsedNode.ranges) {
  17990. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17991. var data = parsedNode.ranges[index];
  17992. node.createAnimationRange(data.name, data.from, data.to);
  17993. }
  17994. }
  17995. };
  17996. __decorate([
  17997. BABYLON.serialize()
  17998. ], Node.prototype, "name", void 0);
  17999. __decorate([
  18000. BABYLON.serialize()
  18001. ], Node.prototype, "id", void 0);
  18002. __decorate([
  18003. BABYLON.serialize()
  18004. ], Node.prototype, "uniqueId", void 0);
  18005. __decorate([
  18006. BABYLON.serialize()
  18007. ], Node.prototype, "state", void 0);
  18008. __decorate([
  18009. BABYLON.serialize()
  18010. ], Node.prototype, "metadata", void 0);
  18011. return Node;
  18012. }());
  18013. BABYLON.Node = Node;
  18014. })(BABYLON || (BABYLON = {}));
  18015. //# sourceMappingURL=babylon.node.js.map
  18016. var BABYLON;
  18017. (function (BABYLON) {
  18018. var BoundingSphere = /** @class */ (function () {
  18019. /**
  18020. * Creates a new bounding sphere
  18021. * @param min defines the minimum vector (in local space)
  18022. * @param max defines the maximum vector (in local space)
  18023. */
  18024. function BoundingSphere(min, max) {
  18025. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18026. this.reConstruct(min, max);
  18027. }
  18028. /**
  18029. * Recreates the entire bounding sphere from scratch
  18030. * @param min defines the new minimum vector (in local space)
  18031. * @param max defines the new maximum vector (in local space)
  18032. */
  18033. BoundingSphere.prototype.reConstruct = function (min, max) {
  18034. this.minimum = min.clone();
  18035. this.maximum = max.clone();
  18036. var distance = BABYLON.Vector3.Distance(min, max);
  18037. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18038. this.radius = distance * 0.5;
  18039. this.centerWorld = BABYLON.Vector3.Zero();
  18040. this._update(BABYLON.Matrix.Identity());
  18041. };
  18042. // Methods
  18043. BoundingSphere.prototype._update = function (world) {
  18044. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18045. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18046. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18047. };
  18048. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18049. for (var i = 0; i < 6; i++) {
  18050. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18051. return false;
  18052. }
  18053. return true;
  18054. };
  18055. BoundingSphere.prototype.intersectsPoint = function (point) {
  18056. var x = this.centerWorld.x - point.x;
  18057. var y = this.centerWorld.y - point.y;
  18058. var z = this.centerWorld.z - point.z;
  18059. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18060. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18061. return false;
  18062. return true;
  18063. };
  18064. // Statics
  18065. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18066. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18067. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18068. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18069. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18070. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18071. return false;
  18072. return true;
  18073. };
  18074. return BoundingSphere;
  18075. }());
  18076. BABYLON.BoundingSphere = BoundingSphere;
  18077. })(BABYLON || (BABYLON = {}));
  18078. //# sourceMappingURL=babylon.boundingSphere.js.map
  18079. var BABYLON;
  18080. (function (BABYLON) {
  18081. var BoundingBox = /** @class */ (function () {
  18082. /**
  18083. * Creates a new bounding box
  18084. * @param min defines the minimum vector (in local space)
  18085. * @param max defines the maximum vector (in local space)
  18086. */
  18087. function BoundingBox(min, max) {
  18088. this.vectorsWorld = new Array();
  18089. this.reConstruct(min, max);
  18090. }
  18091. // Methods
  18092. /**
  18093. * Recreates the entire bounding box from scratch
  18094. * @param min defines the new minimum vector (in local space)
  18095. * @param max defines the new maximum vector (in local space)
  18096. */
  18097. BoundingBox.prototype.reConstruct = function (min, max) {
  18098. this.minimum = min.clone();
  18099. this.maximum = max.clone();
  18100. // Bounding vectors
  18101. this.vectors = new Array();
  18102. this.vectors.push(this.minimum.clone());
  18103. this.vectors.push(this.maximum.clone());
  18104. this.vectors.push(this.minimum.clone());
  18105. this.vectors[2].x = this.maximum.x;
  18106. this.vectors.push(this.minimum.clone());
  18107. this.vectors[3].y = this.maximum.y;
  18108. this.vectors.push(this.minimum.clone());
  18109. this.vectors[4].z = this.maximum.z;
  18110. this.vectors.push(this.maximum.clone());
  18111. this.vectors[5].z = this.minimum.z;
  18112. this.vectors.push(this.maximum.clone());
  18113. this.vectors[6].x = this.minimum.x;
  18114. this.vectors.push(this.maximum.clone());
  18115. this.vectors[7].y = this.minimum.y;
  18116. // OBB
  18117. this.center = this.maximum.add(this.minimum).scale(0.5);
  18118. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18119. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18120. // World
  18121. for (var index = 0; index < this.vectors.length; index++) {
  18122. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18123. }
  18124. this.minimumWorld = BABYLON.Vector3.Zero();
  18125. this.maximumWorld = BABYLON.Vector3.Zero();
  18126. this.centerWorld = BABYLON.Vector3.Zero();
  18127. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18128. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18129. };
  18130. BoundingBox.prototype.getWorldMatrix = function () {
  18131. return this._worldMatrix;
  18132. };
  18133. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18134. this._worldMatrix.copyFrom(matrix);
  18135. return this;
  18136. };
  18137. BoundingBox.prototype._update = function (world) {
  18138. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18139. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18140. for (var index = 0; index < this.vectors.length; index++) {
  18141. var v = this.vectorsWorld[index];
  18142. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18143. if (v.x < this.minimumWorld.x)
  18144. this.minimumWorld.x = v.x;
  18145. if (v.y < this.minimumWorld.y)
  18146. this.minimumWorld.y = v.y;
  18147. if (v.z < this.minimumWorld.z)
  18148. this.minimumWorld.z = v.z;
  18149. if (v.x > this.maximumWorld.x)
  18150. this.maximumWorld.x = v.x;
  18151. if (v.y > this.maximumWorld.y)
  18152. this.maximumWorld.y = v.y;
  18153. if (v.z > this.maximumWorld.z)
  18154. this.maximumWorld.z = v.z;
  18155. }
  18156. // Extend
  18157. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18158. this.extendSizeWorld.scaleInPlace(0.5);
  18159. // OBB
  18160. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18161. this.centerWorld.scaleInPlace(0.5);
  18162. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18163. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18164. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18165. this._worldMatrix = world;
  18166. };
  18167. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18168. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18169. };
  18170. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18171. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18172. };
  18173. BoundingBox.prototype.intersectsPoint = function (point) {
  18174. var delta = -BABYLON.Epsilon;
  18175. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18176. return false;
  18177. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18178. return false;
  18179. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18180. return false;
  18181. return true;
  18182. };
  18183. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18184. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18185. };
  18186. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18187. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18188. return false;
  18189. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18190. return false;
  18191. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18192. return false;
  18193. return true;
  18194. };
  18195. // Statics
  18196. BoundingBox.Intersects = function (box0, box1) {
  18197. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18198. return false;
  18199. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18200. return false;
  18201. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18202. return false;
  18203. return true;
  18204. };
  18205. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18206. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18207. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18208. return (num <= (sphereRadius * sphereRadius));
  18209. };
  18210. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18211. for (var p = 0; p < 6; p++) {
  18212. for (var i = 0; i < 8; i++) {
  18213. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18214. return false;
  18215. }
  18216. }
  18217. }
  18218. return true;
  18219. };
  18220. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18221. for (var p = 0; p < 6; p++) {
  18222. var inCount = 8;
  18223. for (var i = 0; i < 8; i++) {
  18224. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18225. --inCount;
  18226. }
  18227. else {
  18228. break;
  18229. }
  18230. }
  18231. if (inCount === 0)
  18232. return false;
  18233. }
  18234. return true;
  18235. };
  18236. return BoundingBox;
  18237. }());
  18238. BABYLON.BoundingBox = BoundingBox;
  18239. })(BABYLON || (BABYLON = {}));
  18240. //# sourceMappingURL=babylon.boundingBox.js.map
  18241. var BABYLON;
  18242. (function (BABYLON) {
  18243. var computeBoxExtents = function (axis, box) {
  18244. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18245. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18246. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18247. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18248. var r = r0 + r1 + r2;
  18249. return {
  18250. min: p - r,
  18251. max: p + r
  18252. };
  18253. };
  18254. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18255. var axisOverlap = function (axis, box0, box1) {
  18256. var result0 = computeBoxExtents(axis, box0);
  18257. var result1 = computeBoxExtents(axis, box1);
  18258. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18259. };
  18260. var BoundingInfo = /** @class */ (function () {
  18261. function BoundingInfo(minimum, maximum) {
  18262. this.minimum = minimum;
  18263. this.maximum = maximum;
  18264. this._isLocked = false;
  18265. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18266. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18267. }
  18268. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18269. get: function () {
  18270. return this._isLocked;
  18271. },
  18272. set: function (value) {
  18273. this._isLocked = value;
  18274. },
  18275. enumerable: true,
  18276. configurable: true
  18277. });
  18278. // Methods
  18279. BoundingInfo.prototype.update = function (world) {
  18280. if (this._isLocked) {
  18281. return;
  18282. }
  18283. this.boundingBox._update(world);
  18284. this.boundingSphere._update(world);
  18285. };
  18286. /**
  18287. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18288. * @param center New center of the bounding info
  18289. * @param extend New extend of the bounding info
  18290. */
  18291. BoundingInfo.prototype.centerOn = function (center, extend) {
  18292. this.minimum = center.subtract(extend);
  18293. this.maximum = center.add(extend);
  18294. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18295. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18296. return this;
  18297. };
  18298. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18299. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18300. return false;
  18301. return this.boundingBox.isInFrustum(frustumPlanes);
  18302. };
  18303. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18304. /**
  18305. * Gets the world distance between the min and max points of the bounding box
  18306. */
  18307. get: function () {
  18308. var boundingBox = this.boundingBox;
  18309. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18310. return size.length();
  18311. },
  18312. enumerable: true,
  18313. configurable: true
  18314. });
  18315. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18316. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18317. };
  18318. BoundingInfo.prototype._checkCollision = function (collider) {
  18319. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18320. };
  18321. BoundingInfo.prototype.intersectsPoint = function (point) {
  18322. if (!this.boundingSphere.centerWorld) {
  18323. return false;
  18324. }
  18325. if (!this.boundingSphere.intersectsPoint(point)) {
  18326. return false;
  18327. }
  18328. if (!this.boundingBox.intersectsPoint(point)) {
  18329. return false;
  18330. }
  18331. return true;
  18332. };
  18333. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18334. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18335. return false;
  18336. }
  18337. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18338. return false;
  18339. }
  18340. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18341. return false;
  18342. }
  18343. if (!precise) {
  18344. return true;
  18345. }
  18346. var box0 = this.boundingBox;
  18347. var box1 = boundingInfo.boundingBox;
  18348. if (!axisOverlap(box0.directions[0], box0, box1))
  18349. return false;
  18350. if (!axisOverlap(box0.directions[1], box0, box1))
  18351. return false;
  18352. if (!axisOverlap(box0.directions[2], box0, box1))
  18353. return false;
  18354. if (!axisOverlap(box1.directions[0], box0, box1))
  18355. return false;
  18356. if (!axisOverlap(box1.directions[1], box0, box1))
  18357. return false;
  18358. if (!axisOverlap(box1.directions[2], box0, box1))
  18359. return false;
  18360. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18361. return false;
  18362. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18363. return false;
  18364. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18365. return false;
  18366. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18367. return false;
  18368. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18369. return false;
  18370. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18371. return false;
  18372. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18373. return false;
  18374. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18375. return false;
  18376. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18377. return false;
  18378. return true;
  18379. };
  18380. return BoundingInfo;
  18381. }());
  18382. BABYLON.BoundingInfo = BoundingInfo;
  18383. })(BABYLON || (BABYLON = {}));
  18384. //# sourceMappingURL=babylon.boundingInfo.js.map
  18385. var BABYLON;
  18386. (function (BABYLON) {
  18387. var TransformNode = /** @class */ (function (_super) {
  18388. __extends(TransformNode, _super);
  18389. function TransformNode(name, scene, isPure) {
  18390. if (scene === void 0) { scene = null; }
  18391. if (isPure === void 0) { isPure = true; }
  18392. var _this = _super.call(this, name, scene) || this;
  18393. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18394. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18395. _this._up = new BABYLON.Vector3(0, 1, 0);
  18396. _this._right = new BABYLON.Vector3(1, 0, 0);
  18397. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18398. // Properties
  18399. _this._rotation = BABYLON.Vector3.Zero();
  18400. _this._scaling = BABYLON.Vector3.One();
  18401. _this._isDirty = false;
  18402. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18403. _this.scalingDeterminant = 1;
  18404. _this.infiniteDistance = false;
  18405. _this.position = BABYLON.Vector3.Zero();
  18406. _this._localWorld = BABYLON.Matrix.Zero();
  18407. _this._worldMatrix = BABYLON.Matrix.Zero();
  18408. _this._worldMatrixDeterminant = 0;
  18409. _this._absolutePosition = BABYLON.Vector3.Zero();
  18410. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18411. _this._postMultiplyPivotMatrix = false;
  18412. _this._isWorldMatrixFrozen = false;
  18413. /**
  18414. * An event triggered after the world matrix is updated
  18415. */
  18416. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18417. _this._nonUniformScaling = false;
  18418. if (isPure) {
  18419. _this.getScene().addTransformNode(_this);
  18420. }
  18421. return _this;
  18422. }
  18423. /**
  18424. * Gets a string idenfifying the name of the class
  18425. * @returns "TransformNode" string
  18426. */
  18427. TransformNode.prototype.getClassName = function () {
  18428. return "TransformNode";
  18429. };
  18430. Object.defineProperty(TransformNode.prototype, "rotation", {
  18431. /**
  18432. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18433. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18434. * Default : (0.0, 0.0, 0.0)
  18435. */
  18436. get: function () {
  18437. return this._rotation;
  18438. },
  18439. set: function (newRotation) {
  18440. this._rotation = newRotation;
  18441. },
  18442. enumerable: true,
  18443. configurable: true
  18444. });
  18445. Object.defineProperty(TransformNode.prototype, "scaling", {
  18446. /**
  18447. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18448. * Default : (1.0, 1.0, 1.0)
  18449. */
  18450. get: function () {
  18451. return this._scaling;
  18452. },
  18453. /**
  18454. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18455. * Default : (1.0, 1.0, 1.0)
  18456. */
  18457. set: function (newScaling) {
  18458. this._scaling = newScaling;
  18459. },
  18460. enumerable: true,
  18461. configurable: true
  18462. });
  18463. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18464. /**
  18465. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18466. * It's null by default.
  18467. * 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)
  18468. */
  18469. get: function () {
  18470. return this._rotationQuaternion;
  18471. },
  18472. set: function (quaternion) {
  18473. this._rotationQuaternion = quaternion;
  18474. //reset the rotation vector.
  18475. if (quaternion && this.rotation.length()) {
  18476. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18477. }
  18478. },
  18479. enumerable: true,
  18480. configurable: true
  18481. });
  18482. Object.defineProperty(TransformNode.prototype, "forward", {
  18483. /**
  18484. * The forward direction of that transform in world space.
  18485. */
  18486. get: function () {
  18487. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18488. },
  18489. enumerable: true,
  18490. configurable: true
  18491. });
  18492. Object.defineProperty(TransformNode.prototype, "up", {
  18493. /**
  18494. * The up direction of that transform in world space.
  18495. */
  18496. get: function () {
  18497. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18498. },
  18499. enumerable: true,
  18500. configurable: true
  18501. });
  18502. Object.defineProperty(TransformNode.prototype, "right", {
  18503. /**
  18504. * The right direction of that transform in world space.
  18505. */
  18506. get: function () {
  18507. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18508. },
  18509. enumerable: true,
  18510. configurable: true
  18511. });
  18512. /**
  18513. * Returns the latest update of the World matrix
  18514. * Returns a Matrix.
  18515. */
  18516. TransformNode.prototype.getWorldMatrix = function () {
  18517. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18518. this.computeWorldMatrix();
  18519. }
  18520. return this._worldMatrix;
  18521. };
  18522. /** @hidden */
  18523. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18524. return this._worldMatrixDeterminant;
  18525. };
  18526. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18527. /**
  18528. * Returns directly the latest state of the mesh World matrix.
  18529. * A Matrix is returned.
  18530. */
  18531. get: function () {
  18532. return this._worldMatrix;
  18533. },
  18534. enumerable: true,
  18535. configurable: true
  18536. });
  18537. /**
  18538. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18539. * Returns the TransformNode.
  18540. */
  18541. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18542. this._poseMatrix.copyFrom(matrix);
  18543. return this;
  18544. };
  18545. /**
  18546. * Returns the mesh Pose matrix.
  18547. * Returned object : Matrix
  18548. */
  18549. TransformNode.prototype.getPoseMatrix = function () {
  18550. return this._poseMatrix;
  18551. };
  18552. TransformNode.prototype._isSynchronized = function () {
  18553. if (this._isDirty) {
  18554. return false;
  18555. }
  18556. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18557. return false;
  18558. if (this._cache.pivotMatrixUpdated) {
  18559. return false;
  18560. }
  18561. if (this.infiniteDistance) {
  18562. return false;
  18563. }
  18564. if (!this._cache.position.equals(this.position))
  18565. return false;
  18566. if (this.rotationQuaternion) {
  18567. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18568. return false;
  18569. }
  18570. if (!this._cache.rotation.equals(this.rotation))
  18571. return false;
  18572. if (!this._cache.scaling.equals(this.scaling))
  18573. return false;
  18574. return true;
  18575. };
  18576. TransformNode.prototype._initCache = function () {
  18577. _super.prototype._initCache.call(this);
  18578. this._cache.localMatrixUpdated = false;
  18579. this._cache.position = BABYLON.Vector3.Zero();
  18580. this._cache.scaling = BABYLON.Vector3.Zero();
  18581. this._cache.rotation = BABYLON.Vector3.Zero();
  18582. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18583. this._cache.billboardMode = -1;
  18584. };
  18585. TransformNode.prototype.markAsDirty = function (property) {
  18586. if (property === "rotation") {
  18587. this.rotationQuaternion = null;
  18588. }
  18589. this._currentRenderId = Number.MAX_VALUE;
  18590. this._isDirty = true;
  18591. return this;
  18592. };
  18593. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18594. /**
  18595. * Returns the current mesh absolute position.
  18596. * Retuns a Vector3.
  18597. */
  18598. get: function () {
  18599. return this._absolutePosition;
  18600. },
  18601. enumerable: true,
  18602. configurable: true
  18603. });
  18604. /**
  18605. * Sets a new matrix to apply before all other transformation
  18606. * @param matrix defines the transform matrix
  18607. * @returns the current TransformNode
  18608. */
  18609. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18610. return this.setPivotMatrix(matrix, false);
  18611. };
  18612. /**
  18613. * Sets a new pivot matrix to the current node
  18614. * @param matrix defines the new pivot matrix to use
  18615. * @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
  18616. * @returns the current TransformNode
  18617. */
  18618. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18619. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18620. this._pivotMatrix = matrix.clone();
  18621. this._cache.pivotMatrixUpdated = true;
  18622. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18623. if (this._postMultiplyPivotMatrix) {
  18624. if (!this._pivotMatrixInverse) {
  18625. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18626. }
  18627. else {
  18628. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18629. }
  18630. }
  18631. return this;
  18632. };
  18633. /**
  18634. * Returns the mesh pivot matrix.
  18635. * Default : Identity.
  18636. * A Matrix is returned.
  18637. */
  18638. TransformNode.prototype.getPivotMatrix = function () {
  18639. return this._pivotMatrix;
  18640. };
  18641. /**
  18642. * Prevents the World matrix to be computed any longer.
  18643. * Returns the TransformNode.
  18644. */
  18645. TransformNode.prototype.freezeWorldMatrix = function () {
  18646. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18647. this.computeWorldMatrix(true);
  18648. this._isWorldMatrixFrozen = true;
  18649. return this;
  18650. };
  18651. /**
  18652. * Allows back the World matrix computation.
  18653. * Returns the TransformNode.
  18654. */
  18655. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18656. this._isWorldMatrixFrozen = false;
  18657. this.computeWorldMatrix(true);
  18658. return this;
  18659. };
  18660. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18661. /**
  18662. * True if the World matrix has been frozen.
  18663. * Returns a boolean.
  18664. */
  18665. get: function () {
  18666. return this._isWorldMatrixFrozen;
  18667. },
  18668. enumerable: true,
  18669. configurable: true
  18670. });
  18671. /**
  18672. * Retuns the mesh absolute position in the World.
  18673. * Returns a Vector3.
  18674. */
  18675. TransformNode.prototype.getAbsolutePosition = function () {
  18676. this.computeWorldMatrix();
  18677. return this._absolutePosition;
  18678. };
  18679. /**
  18680. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18681. * Returns the TransformNode.
  18682. */
  18683. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18684. if (!absolutePosition) {
  18685. return this;
  18686. }
  18687. var absolutePositionX;
  18688. var absolutePositionY;
  18689. var absolutePositionZ;
  18690. if (absolutePosition.x === undefined) {
  18691. if (arguments.length < 3) {
  18692. return this;
  18693. }
  18694. absolutePositionX = arguments[0];
  18695. absolutePositionY = arguments[1];
  18696. absolutePositionZ = arguments[2];
  18697. }
  18698. else {
  18699. absolutePositionX = absolutePosition.x;
  18700. absolutePositionY = absolutePosition.y;
  18701. absolutePositionZ = absolutePosition.z;
  18702. }
  18703. if (this.parent) {
  18704. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18705. invertParentWorldMatrix.invert();
  18706. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18707. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18708. }
  18709. else {
  18710. this.position.x = absolutePositionX;
  18711. this.position.y = absolutePositionY;
  18712. this.position.z = absolutePositionZ;
  18713. }
  18714. return this;
  18715. };
  18716. /**
  18717. * Sets the mesh position in its local space.
  18718. * Returns the TransformNode.
  18719. */
  18720. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18721. this.computeWorldMatrix();
  18722. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18723. return this;
  18724. };
  18725. /**
  18726. * Returns the mesh position in the local space from the current World matrix values.
  18727. * Returns a new Vector3.
  18728. */
  18729. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18730. this.computeWorldMatrix();
  18731. var invLocalWorldMatrix = this._localWorld.clone();
  18732. invLocalWorldMatrix.invert();
  18733. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18734. };
  18735. /**
  18736. * Translates the mesh along the passed Vector3 in its local space.
  18737. * Returns the TransformNode.
  18738. */
  18739. TransformNode.prototype.locallyTranslate = function (vector3) {
  18740. this.computeWorldMatrix(true);
  18741. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18742. return this;
  18743. };
  18744. /**
  18745. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18746. * @param targetPoint the position (must be in same space as current mesh) to look at
  18747. * @param yawCor optional yaw (y-axis) correction in radians
  18748. * @param pitchCor optional pitch (x-axis) correction in radians
  18749. * @param rollCor optional roll (z-axis) correction in radians
  18750. * @param space the choosen space of the target
  18751. * @returns the TransformNode.
  18752. */
  18753. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18754. if (yawCor === void 0) { yawCor = 0; }
  18755. if (pitchCor === void 0) { pitchCor = 0; }
  18756. if (rollCor === void 0) { rollCor = 0; }
  18757. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18758. var dv = TransformNode._lookAtVectorCache;
  18759. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18760. targetPoint.subtractToRef(pos, dv);
  18761. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18762. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18763. var pitch = Math.atan2(dv.y, len);
  18764. if (this.rotationQuaternion) {
  18765. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18766. }
  18767. else {
  18768. this.rotation.x = pitch + pitchCor;
  18769. this.rotation.y = yaw + yawCor;
  18770. this.rotation.z = rollCor;
  18771. }
  18772. return this;
  18773. };
  18774. /**
  18775. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18776. * This Vector3 is expressed in the World space.
  18777. */
  18778. TransformNode.prototype.getDirection = function (localAxis) {
  18779. var result = BABYLON.Vector3.Zero();
  18780. this.getDirectionToRef(localAxis, result);
  18781. return result;
  18782. };
  18783. /**
  18784. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18785. * localAxis is expressed in the mesh local space.
  18786. * result is computed in the Wordl space from the mesh World matrix.
  18787. * Returns the TransformNode.
  18788. */
  18789. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18790. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18791. return this;
  18792. };
  18793. /**
  18794. * Sets a new pivot point to the current node
  18795. * @param point defines the new pivot point to use
  18796. * @param space defines if the point is in world or local space (local by default)
  18797. * @returns the current TransformNode
  18798. */
  18799. TransformNode.prototype.setPivotPoint = function (point, space) {
  18800. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18801. if (this.getScene().getRenderId() == 0) {
  18802. this.computeWorldMatrix(true);
  18803. }
  18804. var wm = this.getWorldMatrix();
  18805. if (space == BABYLON.Space.WORLD) {
  18806. var tmat = BABYLON.Tmp.Matrix[0];
  18807. wm.invertToRef(tmat);
  18808. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18809. }
  18810. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18811. };
  18812. /**
  18813. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18814. */
  18815. TransformNode.prototype.getPivotPoint = function () {
  18816. var point = BABYLON.Vector3.Zero();
  18817. this.getPivotPointToRef(point);
  18818. return point;
  18819. };
  18820. /**
  18821. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18822. * Returns the TransformNode.
  18823. */
  18824. TransformNode.prototype.getPivotPointToRef = function (result) {
  18825. result.x = -this._pivotMatrix.m[12];
  18826. result.y = -this._pivotMatrix.m[13];
  18827. result.z = -this._pivotMatrix.m[14];
  18828. return this;
  18829. };
  18830. /**
  18831. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18832. */
  18833. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18834. var point = BABYLON.Vector3.Zero();
  18835. this.getAbsolutePivotPointToRef(point);
  18836. return point;
  18837. };
  18838. /**
  18839. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18840. * Returns the TransformNode.
  18841. */
  18842. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18843. result.x = this._pivotMatrix.m[12];
  18844. result.y = this._pivotMatrix.m[13];
  18845. result.z = this._pivotMatrix.m[14];
  18846. this.getPivotPointToRef(result);
  18847. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18848. return this;
  18849. };
  18850. /**
  18851. * Defines the passed node as the parent of the current node.
  18852. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18853. * Returns the TransformNode.
  18854. */
  18855. TransformNode.prototype.setParent = function (node) {
  18856. if (node === null) {
  18857. var rotation = BABYLON.Tmp.Quaternion[0];
  18858. var position = BABYLON.Tmp.Vector3[0];
  18859. var scale = BABYLON.Tmp.Vector3[1];
  18860. if (this.parent && this.parent.computeWorldMatrix) {
  18861. this.parent.computeWorldMatrix(true);
  18862. }
  18863. this.computeWorldMatrix(true);
  18864. this.getWorldMatrix().decompose(scale, rotation, position);
  18865. if (this.rotationQuaternion) {
  18866. this.rotationQuaternion.copyFrom(rotation);
  18867. }
  18868. else {
  18869. rotation.toEulerAnglesToRef(this.rotation);
  18870. }
  18871. this.scaling.x = scale.x;
  18872. this.scaling.y = scale.y;
  18873. this.scaling.z = scale.z;
  18874. this.position.x = position.x;
  18875. this.position.y = position.y;
  18876. this.position.z = position.z;
  18877. }
  18878. else {
  18879. var rotation = BABYLON.Tmp.Quaternion[0];
  18880. var position = BABYLON.Tmp.Vector3[0];
  18881. var scale = BABYLON.Tmp.Vector3[1];
  18882. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18883. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18884. this.computeWorldMatrix(true);
  18885. node.computeWorldMatrix(true);
  18886. node.getWorldMatrix().invertToRef(invParentMatrix);
  18887. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18888. diffMatrix.decompose(scale, rotation, position);
  18889. if (this.rotationQuaternion) {
  18890. this.rotationQuaternion.copyFrom(rotation);
  18891. }
  18892. else {
  18893. rotation.toEulerAnglesToRef(this.rotation);
  18894. }
  18895. this.position.x = position.x;
  18896. this.position.y = position.y;
  18897. this.position.z = position.z;
  18898. this.scaling.x = scale.x;
  18899. this.scaling.y = scale.y;
  18900. this.scaling.z = scale.z;
  18901. }
  18902. this.parent = node;
  18903. return this;
  18904. };
  18905. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18906. get: function () {
  18907. return this._nonUniformScaling;
  18908. },
  18909. enumerable: true,
  18910. configurable: true
  18911. });
  18912. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18913. if (this._nonUniformScaling === value) {
  18914. return false;
  18915. }
  18916. this._nonUniformScaling = true;
  18917. return true;
  18918. };
  18919. /**
  18920. * Attach the current TransformNode to another TransformNode associated with a bone
  18921. * @param bone Bone affecting the TransformNode
  18922. * @param affectedTransformNode TransformNode associated with the bone
  18923. */
  18924. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18925. this._transformToBoneReferal = affectedTransformNode;
  18926. this.parent = bone;
  18927. if (bone.getWorldMatrix().determinant() < 0) {
  18928. this.scalingDeterminant *= -1;
  18929. }
  18930. return this;
  18931. };
  18932. TransformNode.prototype.detachFromBone = function () {
  18933. if (!this.parent) {
  18934. return this;
  18935. }
  18936. if (this.parent.getWorldMatrix().determinant() < 0) {
  18937. this.scalingDeterminant *= -1;
  18938. }
  18939. this._transformToBoneReferal = null;
  18940. this.parent = null;
  18941. return this;
  18942. };
  18943. /**
  18944. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18945. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18946. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18947. * The passed axis is also normalized.
  18948. * Returns the TransformNode.
  18949. */
  18950. TransformNode.prototype.rotate = function (axis, amount, space) {
  18951. axis.normalize();
  18952. if (!this.rotationQuaternion) {
  18953. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18954. this.rotation = BABYLON.Vector3.Zero();
  18955. }
  18956. var rotationQuaternion;
  18957. if (!space || space === BABYLON.Space.LOCAL) {
  18958. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18959. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18960. }
  18961. else {
  18962. if (this.parent) {
  18963. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18964. invertParentWorldMatrix.invert();
  18965. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18966. }
  18967. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18968. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18969. }
  18970. return this;
  18971. };
  18972. /**
  18973. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18974. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18975. * The passed axis is also normalized.
  18976. * Returns the TransformNode.
  18977. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18978. */
  18979. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18980. axis.normalize();
  18981. if (!this.rotationQuaternion) {
  18982. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18983. this.rotation.copyFromFloats(0, 0, 0);
  18984. }
  18985. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18986. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18987. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18988. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18989. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18990. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18991. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18992. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18993. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18994. return this;
  18995. };
  18996. /**
  18997. * Translates the mesh along the axis vector for the passed distance in the given space.
  18998. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18999. * Returns the TransformNode.
  19000. */
  19001. TransformNode.prototype.translate = function (axis, distance, space) {
  19002. var displacementVector = axis.scale(distance);
  19003. if (!space || space === BABYLON.Space.LOCAL) {
  19004. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19005. this.setPositionWithLocalVector(tempV3);
  19006. }
  19007. else {
  19008. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19009. }
  19010. return this;
  19011. };
  19012. /**
  19013. * Adds a rotation step to the mesh current rotation.
  19014. * x, y, z are Euler angles expressed in radians.
  19015. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19016. * This means this rotation is made in the mesh local space only.
  19017. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19018. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19019. * ```javascript
  19020. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19021. * ```
  19022. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19023. * 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.
  19024. * Returns the TransformNode.
  19025. */
  19026. TransformNode.prototype.addRotation = function (x, y, z) {
  19027. var rotationQuaternion;
  19028. if (this.rotationQuaternion) {
  19029. rotationQuaternion = this.rotationQuaternion;
  19030. }
  19031. else {
  19032. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19033. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19034. }
  19035. var accumulation = BABYLON.Tmp.Quaternion[0];
  19036. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19037. rotationQuaternion.multiplyInPlace(accumulation);
  19038. if (!this.rotationQuaternion) {
  19039. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19040. }
  19041. return this;
  19042. };
  19043. /**
  19044. * Computes the mesh World matrix and returns it.
  19045. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19046. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19047. * If the parameter `force`is set to `true`, the actual computation is done.
  19048. * Returns the mesh World Matrix.
  19049. */
  19050. TransformNode.prototype.computeWorldMatrix = function (force) {
  19051. if (this._isWorldMatrixFrozen) {
  19052. return this._worldMatrix;
  19053. }
  19054. if (!force && this.isSynchronized(true)) {
  19055. this._currentRenderId = this.getScene().getRenderId();
  19056. return this._worldMatrix;
  19057. }
  19058. this._cache.position.copyFrom(this.position);
  19059. this._cache.scaling.copyFrom(this.scaling);
  19060. this._cache.pivotMatrixUpdated = false;
  19061. this._cache.billboardMode = this.billboardMode;
  19062. this._currentRenderId = this.getScene().getRenderId();
  19063. this._childRenderId = this.getScene().getRenderId();
  19064. this._isDirty = false;
  19065. // Scaling
  19066. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19067. // Rotation
  19068. //rotate, if quaternion is set and rotation was used
  19069. if (this.rotationQuaternion) {
  19070. var len = this.rotation.length();
  19071. if (len) {
  19072. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19073. this.rotation.copyFromFloats(0, 0, 0);
  19074. }
  19075. }
  19076. if (this.rotationQuaternion) {
  19077. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19078. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19079. }
  19080. else {
  19081. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19082. this._cache.rotation.copyFrom(this.rotation);
  19083. }
  19084. // Translation
  19085. var camera = this.getScene().activeCamera;
  19086. if (this.infiniteDistance && !this.parent && camera) {
  19087. var cameraWorldMatrix = camera.getWorldMatrix();
  19088. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19089. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19090. }
  19091. else {
  19092. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19093. }
  19094. // Composing transformations
  19095. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19096. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19097. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19098. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19099. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19100. // Need to decompose each rotation here
  19101. var currentPosition = BABYLON.Tmp.Vector3[3];
  19102. if (this.parent && this.parent.getWorldMatrix) {
  19103. if (this._transformToBoneReferal) {
  19104. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19105. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19106. }
  19107. else {
  19108. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19109. }
  19110. }
  19111. else {
  19112. currentPosition.copyFrom(this.position);
  19113. }
  19114. currentPosition.subtractInPlace(camera.globalPosition);
  19115. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19116. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19117. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19118. }
  19119. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19120. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19121. }
  19122. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19123. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19124. }
  19125. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19126. }
  19127. else {
  19128. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19129. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19130. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19131. }
  19132. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19133. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19134. }
  19135. // Local world
  19136. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19137. // Parent
  19138. if (this.parent && this.parent.getWorldMatrix) {
  19139. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19140. if (this._transformToBoneReferal) {
  19141. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19142. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19143. }
  19144. else {
  19145. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19146. }
  19147. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19148. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19149. this._worldMatrix.copyFrom(this._localWorld);
  19150. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19151. }
  19152. else {
  19153. if (this._transformToBoneReferal) {
  19154. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19155. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19156. }
  19157. else {
  19158. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19159. }
  19160. }
  19161. this._markSyncedWithParent();
  19162. }
  19163. else {
  19164. this._worldMatrix.copyFrom(this._localWorld);
  19165. }
  19166. // Post multiply inverse of pivotMatrix
  19167. if (this._postMultiplyPivotMatrix) {
  19168. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19169. }
  19170. // Normal matrix
  19171. if (this.scaling.isNonUniform) {
  19172. this._updateNonUniformScalingState(true);
  19173. }
  19174. else if (this.parent && this.parent._nonUniformScaling) {
  19175. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19176. }
  19177. else {
  19178. this._updateNonUniformScalingState(false);
  19179. }
  19180. this._afterComputeWorldMatrix();
  19181. // Absolute position
  19182. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19183. // Callbacks
  19184. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19185. if (!this._poseMatrix) {
  19186. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19187. }
  19188. // Cache the determinant
  19189. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19190. return this._worldMatrix;
  19191. };
  19192. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19193. };
  19194. /**
  19195. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19196. * @param func: callback function to add
  19197. *
  19198. * Returns the TransformNode.
  19199. */
  19200. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19201. this.onAfterWorldMatrixUpdateObservable.add(func);
  19202. return this;
  19203. };
  19204. /**
  19205. * Removes a registered callback function.
  19206. * Returns the TransformNode.
  19207. */
  19208. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19209. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19210. return this;
  19211. };
  19212. /**
  19213. * Clone the current transform node
  19214. * Returns the new transform node
  19215. * @param name Name of the new clone
  19216. * @param newParent New parent for the clone
  19217. * @param doNotCloneChildren Do not clone children hierarchy
  19218. */
  19219. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19220. var _this = this;
  19221. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19222. result.name = name;
  19223. result.id = name;
  19224. if (newParent) {
  19225. result.parent = newParent;
  19226. }
  19227. if (!doNotCloneChildren) {
  19228. // Children
  19229. var directDescendants = this.getDescendants(true);
  19230. for (var index = 0; index < directDescendants.length; index++) {
  19231. var child = directDescendants[index];
  19232. if (child.clone) {
  19233. child.clone(name + "." + child.name, result);
  19234. }
  19235. }
  19236. }
  19237. return result;
  19238. };
  19239. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19240. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19241. serializationObject.type = this.getClassName();
  19242. // Parent
  19243. if (this.parent) {
  19244. serializationObject.parentId = this.parent.id;
  19245. }
  19246. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19247. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19248. }
  19249. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19250. serializationObject.isEnabled = this.isEnabled();
  19251. // Parent
  19252. if (this.parent) {
  19253. serializationObject.parentId = this.parent.id;
  19254. }
  19255. return serializationObject;
  19256. };
  19257. // Statics
  19258. /**
  19259. * Returns a new TransformNode object parsed from the source provided.
  19260. * The parameter `parsedMesh` is the source.
  19261. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19262. */
  19263. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19264. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19265. if (BABYLON.Tags) {
  19266. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19267. }
  19268. if (parsedTransformNode.localMatrix) {
  19269. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19270. }
  19271. else if (parsedTransformNode.pivotMatrix) {
  19272. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19273. }
  19274. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19275. // Parent
  19276. if (parsedTransformNode.parentId) {
  19277. transformNode._waitingParentId = parsedTransformNode.parentId;
  19278. }
  19279. return transformNode;
  19280. };
  19281. /**
  19282. * Releases resources associated with this transform node.
  19283. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19284. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19285. */
  19286. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19287. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19288. // Animations
  19289. this.getScene().stopAnimation(this);
  19290. // Remove from scene
  19291. this.getScene().removeTransformNode(this);
  19292. this.onAfterWorldMatrixUpdateObservable.clear();
  19293. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19294. };
  19295. // Statics
  19296. TransformNode.BILLBOARDMODE_NONE = 0;
  19297. TransformNode.BILLBOARDMODE_X = 1;
  19298. TransformNode.BILLBOARDMODE_Y = 2;
  19299. TransformNode.BILLBOARDMODE_Z = 4;
  19300. TransformNode.BILLBOARDMODE_ALL = 7;
  19301. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19302. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19303. __decorate([
  19304. BABYLON.serializeAsVector3()
  19305. ], TransformNode.prototype, "_rotation", void 0);
  19306. __decorate([
  19307. BABYLON.serializeAsQuaternion()
  19308. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19309. __decorate([
  19310. BABYLON.serializeAsVector3()
  19311. ], TransformNode.prototype, "_scaling", void 0);
  19312. __decorate([
  19313. BABYLON.serialize()
  19314. ], TransformNode.prototype, "billboardMode", void 0);
  19315. __decorate([
  19316. BABYLON.serialize()
  19317. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19318. __decorate([
  19319. BABYLON.serialize()
  19320. ], TransformNode.prototype, "infiniteDistance", void 0);
  19321. __decorate([
  19322. BABYLON.serializeAsVector3()
  19323. ], TransformNode.prototype, "position", void 0);
  19324. return TransformNode;
  19325. }(BABYLON.Node));
  19326. BABYLON.TransformNode = TransformNode;
  19327. })(BABYLON || (BABYLON = {}));
  19328. //# sourceMappingURL=babylon.transformNode.js.map
  19329. var BABYLON;
  19330. (function (BABYLON) {
  19331. /**
  19332. * Class used to store all common mesh properties
  19333. */
  19334. var AbstractMesh = /** @class */ (function (_super) {
  19335. __extends(AbstractMesh, _super);
  19336. // Constructor
  19337. /**
  19338. * Creates a new AbstractMesh
  19339. * @param name defines the name of the mesh
  19340. * @param scene defines the hosting scene
  19341. */
  19342. function AbstractMesh(name, scene) {
  19343. if (scene === void 0) { scene = null; }
  19344. var _this = _super.call(this, name, scene, false) || this;
  19345. _this._facetNb = 0; // facet number
  19346. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19347. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19348. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19349. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19350. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19351. _this._subDiv = {
  19352. max: 1,
  19353. X: 1,
  19354. Y: 1,
  19355. Z: 1
  19356. };
  19357. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19358. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19359. // Events
  19360. /**
  19361. * An event triggered when this mesh collides with another one
  19362. */
  19363. _this.onCollideObservable = new BABYLON.Observable();
  19364. /**
  19365. * An event triggered when the collision's position changes
  19366. */
  19367. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19368. /**
  19369. * An event triggered when material is changed
  19370. */
  19371. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19372. // Properties
  19373. /**
  19374. * Gets or sets the orientation for POV movement & rotation
  19375. */
  19376. _this.definedFacingForward = true;
  19377. /**
  19378. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19379. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19380. * * 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.
  19381. * @see http://doc.babylonjs.com/features/occlusionquery
  19382. */
  19383. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19384. /**
  19385. * 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:
  19386. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19387. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19388. * * 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.
  19389. * @see http://doc.babylonjs.com/features/occlusionquery
  19390. */
  19391. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19392. /**
  19393. * 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.
  19394. * The default value is -1 which means don't break the query and wait till the result
  19395. * @see http://doc.babylonjs.com/features/occlusionquery
  19396. */
  19397. _this.occlusionRetryCount = -1;
  19398. _this._occlusionInternalRetryCounter = 0;
  19399. _this._isOccluded = false;
  19400. _this._isOcclusionQueryInProgress = false;
  19401. _this._visibility = 1.0;
  19402. /** Gets or sets the alpha index used to sort transparent meshes
  19403. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19404. */
  19405. _this.alphaIndex = Number.MAX_VALUE;
  19406. /**
  19407. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19408. */
  19409. _this.isVisible = true;
  19410. /**
  19411. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19412. */
  19413. _this.isPickable = true;
  19414. /**
  19415. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19416. */
  19417. _this.showBoundingBox = false;
  19418. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19419. _this.showSubMeshesBoundingBox = false;
  19420. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19421. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19422. */
  19423. _this.isBlocker = false;
  19424. /**
  19425. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19426. */
  19427. _this.enablePointerMoveEvents = false;
  19428. /**
  19429. * Specifies the rendering group id for this mesh (0 by default)
  19430. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19431. */
  19432. _this.renderingGroupId = 0;
  19433. _this._receiveShadows = false;
  19434. /**
  19435. * Gets or sets a boolean indicating if the outline must be rendered as well
  19436. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19437. */
  19438. _this.renderOutline = false;
  19439. /** Defines color to use when rendering outline */
  19440. _this.outlineColor = BABYLON.Color3.Red();
  19441. /** Define width to use when rendering outline */
  19442. _this.outlineWidth = 0.02;
  19443. /**
  19444. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19445. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19446. */
  19447. _this.renderOverlay = false;
  19448. /** Defines color to use when rendering overlay */
  19449. _this.overlayColor = BABYLON.Color3.Red();
  19450. /** Defines alpha to use when rendering overlay */
  19451. _this.overlayAlpha = 0.5;
  19452. _this._hasVertexAlpha = false;
  19453. _this._useVertexColors = true;
  19454. _this._computeBonesUsingShaders = true;
  19455. _this._numBoneInfluencers = 4;
  19456. _this._applyFog = true;
  19457. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19458. _this.useOctreeForRenderingSelection = true;
  19459. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19460. _this.useOctreeForPicking = true;
  19461. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19462. _this.useOctreeForCollisions = true;
  19463. _this._layerMask = 0x0FFFFFFF;
  19464. /**
  19465. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19466. */
  19467. _this.alwaysSelectAsActiveMesh = false;
  19468. /**
  19469. * Gets or sets the current action manager
  19470. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19471. */
  19472. _this.actionManager = null;
  19473. /**
  19474. * Gets or sets impostor used for physic simulation
  19475. * @see http://doc.babylonjs.com/features/physics_engine
  19476. */
  19477. _this.physicsImpostor = null;
  19478. // Collisions
  19479. _this._checkCollisions = false;
  19480. _this._collisionMask = -1;
  19481. _this._collisionGroup = -1;
  19482. /**
  19483. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19484. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19485. */
  19486. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19487. /**
  19488. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19489. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19490. */
  19491. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19492. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19493. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19494. // Edges
  19495. /**
  19496. * Defines edge width used when edgesRenderer is enabled
  19497. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19498. */
  19499. _this.edgesWidth = 1;
  19500. /**
  19501. * Defines edge color used when edgesRenderer is enabled
  19502. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19503. */
  19504. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19505. // Cache
  19506. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19507. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19508. /** @hidden */
  19509. _this._renderId = 0;
  19510. /** @hidden */
  19511. _this._intersectionsInProgress = new Array();
  19512. /** @hidden */
  19513. _this._unIndexed = false;
  19514. /** @hidden */
  19515. _this._lightSources = new Array();
  19516. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19517. if (collidedMesh === void 0) { collidedMesh = null; }
  19518. //TODO move this to the collision coordinator!
  19519. if (_this.getScene().workerCollisions)
  19520. newPosition.multiplyInPlace(_this._collider._radius);
  19521. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19522. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19523. _this.position.addInPlace(_this._diffPositionForCollisions);
  19524. }
  19525. if (collidedMesh) {
  19526. _this.onCollideObservable.notifyObservers(collidedMesh);
  19527. }
  19528. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19529. };
  19530. _this.getScene().addMesh(_this);
  19531. _this._resyncLightSources();
  19532. return _this;
  19533. }
  19534. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19535. /**
  19536. * No billboard
  19537. */
  19538. get: function () {
  19539. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19540. },
  19541. enumerable: true,
  19542. configurable: true
  19543. });
  19544. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19545. /** Billboard on X axis */
  19546. get: function () {
  19547. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19548. },
  19549. enumerable: true,
  19550. configurable: true
  19551. });
  19552. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19553. /** Billboard on Y axis */
  19554. get: function () {
  19555. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19556. },
  19557. enumerable: true,
  19558. configurable: true
  19559. });
  19560. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19561. /** Billboard on Z axis */
  19562. get: function () {
  19563. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19564. },
  19565. enumerable: true,
  19566. configurable: true
  19567. });
  19568. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19569. /** Billboard on all axes */
  19570. get: function () {
  19571. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19572. },
  19573. enumerable: true,
  19574. configurable: true
  19575. });
  19576. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19577. /**
  19578. * Gets the number of facets in the mesh
  19579. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19580. */
  19581. get: function () {
  19582. return this._facetNb;
  19583. },
  19584. enumerable: true,
  19585. configurable: true
  19586. });
  19587. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19588. /**
  19589. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19590. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19591. */
  19592. get: function () {
  19593. return this._partitioningSubdivisions;
  19594. },
  19595. set: function (nb) {
  19596. this._partitioningSubdivisions = nb;
  19597. },
  19598. enumerable: true,
  19599. configurable: true
  19600. });
  19601. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19602. /**
  19603. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19604. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19605. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19606. */
  19607. get: function () {
  19608. return this._partitioningBBoxRatio;
  19609. },
  19610. set: function (ratio) {
  19611. this._partitioningBBoxRatio = ratio;
  19612. },
  19613. enumerable: true,
  19614. configurable: true
  19615. });
  19616. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19617. /**
  19618. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19619. * Works only for updatable meshes.
  19620. * Doesn't work with multi-materials
  19621. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19622. */
  19623. get: function () {
  19624. return this._facetDepthSort;
  19625. },
  19626. set: function (sort) {
  19627. this._facetDepthSort = sort;
  19628. },
  19629. enumerable: true,
  19630. configurable: true
  19631. });
  19632. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19633. /**
  19634. * The location (Vector3) where the facet depth sort must be computed from.
  19635. * By default, the active camera position.
  19636. * Used only when facet depth sort is enabled
  19637. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19638. */
  19639. get: function () {
  19640. return this._facetDepthSortFrom;
  19641. },
  19642. set: function (location) {
  19643. this._facetDepthSortFrom = location;
  19644. },
  19645. enumerable: true,
  19646. configurable: true
  19647. });
  19648. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19649. /**
  19650. * gets a boolean indicating if facetData is enabled
  19651. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19652. */
  19653. get: function () {
  19654. return this._facetDataEnabled;
  19655. },
  19656. enumerable: true,
  19657. configurable: true
  19658. });
  19659. /** @hidden */
  19660. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19661. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19662. return false;
  19663. }
  19664. this._markSubMeshesAsMiscDirty();
  19665. return true;
  19666. };
  19667. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19668. /** Set a function to call when this mesh collides with another one */
  19669. set: function (callback) {
  19670. if (this._onCollideObserver) {
  19671. this.onCollideObservable.remove(this._onCollideObserver);
  19672. }
  19673. this._onCollideObserver = this.onCollideObservable.add(callback);
  19674. },
  19675. enumerable: true,
  19676. configurable: true
  19677. });
  19678. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19679. /** Set a function to call when the collision's position changes */
  19680. set: function (callback) {
  19681. if (this._onCollisionPositionChangeObserver) {
  19682. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19683. }
  19684. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19685. },
  19686. enumerable: true,
  19687. configurable: true
  19688. });
  19689. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19690. /**
  19691. * 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
  19692. * @see http://doc.babylonjs.com/features/occlusionquery
  19693. */
  19694. get: function () {
  19695. return this._isOccluded;
  19696. },
  19697. set: function (value) {
  19698. this._isOccluded = value;
  19699. },
  19700. enumerable: true,
  19701. configurable: true
  19702. });
  19703. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19704. /**
  19705. * Flag to check the progress status of the query
  19706. * @see http://doc.babylonjs.com/features/occlusionquery
  19707. */
  19708. get: function () {
  19709. return this._isOcclusionQueryInProgress;
  19710. },
  19711. enumerable: true,
  19712. configurable: true
  19713. });
  19714. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19715. /**
  19716. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19717. */
  19718. get: function () {
  19719. return this._visibility;
  19720. },
  19721. /**
  19722. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19723. */
  19724. set: function (value) {
  19725. if (this._visibility === value) {
  19726. return;
  19727. }
  19728. this._visibility = value;
  19729. this._markSubMeshesAsMiscDirty();
  19730. },
  19731. enumerable: true,
  19732. configurable: true
  19733. });
  19734. Object.defineProperty(AbstractMesh.prototype, "material", {
  19735. /** Gets or sets current material */
  19736. get: function () {
  19737. return this._material;
  19738. },
  19739. set: function (value) {
  19740. if (this._material === value) {
  19741. return;
  19742. }
  19743. this._material = value;
  19744. if (this.onMaterialChangedObservable.hasObservers) {
  19745. this.onMaterialChangedObservable.notifyObservers(this);
  19746. }
  19747. if (!this.subMeshes) {
  19748. return;
  19749. }
  19750. this._unBindEffect();
  19751. },
  19752. enumerable: true,
  19753. configurable: true
  19754. });
  19755. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19756. /**
  19757. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19758. * @see http://doc.babylonjs.com/babylon101/shadows
  19759. */
  19760. get: function () {
  19761. return this._receiveShadows;
  19762. },
  19763. set: function (value) {
  19764. if (this._receiveShadows === value) {
  19765. return;
  19766. }
  19767. this._receiveShadows = value;
  19768. this._markSubMeshesAsLightDirty();
  19769. },
  19770. enumerable: true,
  19771. configurable: true
  19772. });
  19773. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19774. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19775. get: function () {
  19776. return this._hasVertexAlpha;
  19777. },
  19778. set: function (value) {
  19779. if (this._hasVertexAlpha === value) {
  19780. return;
  19781. }
  19782. this._hasVertexAlpha = value;
  19783. this._markSubMeshesAsAttributesDirty();
  19784. this._markSubMeshesAsMiscDirty();
  19785. },
  19786. enumerable: true,
  19787. configurable: true
  19788. });
  19789. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19790. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  19791. get: function () {
  19792. return this._useVertexColors;
  19793. },
  19794. set: function (value) {
  19795. if (this._useVertexColors === value) {
  19796. return;
  19797. }
  19798. this._useVertexColors = value;
  19799. this._markSubMeshesAsAttributesDirty();
  19800. },
  19801. enumerable: true,
  19802. configurable: true
  19803. });
  19804. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19805. /**
  19806. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19807. */
  19808. get: function () {
  19809. return this._computeBonesUsingShaders;
  19810. },
  19811. set: function (value) {
  19812. if (this._computeBonesUsingShaders === value) {
  19813. return;
  19814. }
  19815. this._computeBonesUsingShaders = value;
  19816. this._markSubMeshesAsAttributesDirty();
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19822. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19823. get: function () {
  19824. return this._numBoneInfluencers;
  19825. },
  19826. set: function (value) {
  19827. if (this._numBoneInfluencers === value) {
  19828. return;
  19829. }
  19830. this._numBoneInfluencers = value;
  19831. this._markSubMeshesAsAttributesDirty();
  19832. },
  19833. enumerable: true,
  19834. configurable: true
  19835. });
  19836. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19837. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19838. get: function () {
  19839. return this._applyFog;
  19840. },
  19841. set: function (value) {
  19842. if (this._applyFog === value) {
  19843. return;
  19844. }
  19845. this._applyFog = value;
  19846. this._markSubMeshesAsMiscDirty();
  19847. },
  19848. enumerable: true,
  19849. configurable: true
  19850. });
  19851. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19852. /**
  19853. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19854. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19855. */
  19856. get: function () {
  19857. return this._layerMask;
  19858. },
  19859. set: function (value) {
  19860. if (value === this._layerMask) {
  19861. return;
  19862. }
  19863. this._layerMask = value;
  19864. this._resyncLightSources();
  19865. },
  19866. enumerable: true,
  19867. configurable: true
  19868. });
  19869. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19870. /**
  19871. * Gets or sets a collision mask used to mask collisions (default is -1).
  19872. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19873. */
  19874. get: function () {
  19875. return this._collisionMask;
  19876. },
  19877. set: function (mask) {
  19878. this._collisionMask = !isNaN(mask) ? mask : -1;
  19879. },
  19880. enumerable: true,
  19881. configurable: true
  19882. });
  19883. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19884. /**
  19885. * Gets or sets the current collision group mask (-1 by default).
  19886. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19887. */
  19888. get: function () {
  19889. return this._collisionGroup;
  19890. },
  19891. set: function (mask) {
  19892. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19893. },
  19894. enumerable: true,
  19895. configurable: true
  19896. });
  19897. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19898. /** @hidden */
  19899. get: function () {
  19900. return null;
  19901. },
  19902. enumerable: true,
  19903. configurable: true
  19904. });
  19905. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19906. get: function () {
  19907. return this._skeleton;
  19908. },
  19909. /**
  19910. * Gets or sets a skeleton to apply skining transformations
  19911. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19912. */
  19913. set: function (value) {
  19914. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19915. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19916. }
  19917. if (value && value.needInitialSkinMatrix) {
  19918. value._registerMeshWithPoseMatrix(this);
  19919. }
  19920. this._skeleton = value;
  19921. if (!this._skeleton) {
  19922. this._bonesTransformMatrices = null;
  19923. }
  19924. this._markSubMeshesAsAttributesDirty();
  19925. },
  19926. enumerable: true,
  19927. configurable: true
  19928. });
  19929. /**
  19930. * Returns the string "AbstractMesh"
  19931. * @returns "AbstractMesh"
  19932. */
  19933. AbstractMesh.prototype.getClassName = function () {
  19934. return "AbstractMesh";
  19935. };
  19936. /**
  19937. * Gets a string representation of the current mesh
  19938. * @param fullDetails defines a boolean indicating if full details must be included
  19939. * @returns a string representation of the current mesh
  19940. */
  19941. AbstractMesh.prototype.toString = function (fullDetails) {
  19942. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19943. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19944. if (this._skeleton) {
  19945. ret += ", skeleton: " + this._skeleton.name;
  19946. }
  19947. if (fullDetails) {
  19948. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19949. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19950. }
  19951. return ret;
  19952. };
  19953. /** @hidden */
  19954. AbstractMesh.prototype._rebuild = function () {
  19955. if (this._occlusionQuery) {
  19956. this._occlusionQuery = null;
  19957. }
  19958. if (this._edgesRenderer) {
  19959. this._edgesRenderer._rebuild();
  19960. }
  19961. if (!this.subMeshes) {
  19962. return;
  19963. }
  19964. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19965. var subMesh = _a[_i];
  19966. subMesh._rebuild();
  19967. }
  19968. };
  19969. /** @hidden */
  19970. AbstractMesh.prototype._resyncLightSources = function () {
  19971. this._lightSources.length = 0;
  19972. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19973. var light = _a[_i];
  19974. if (!light.isEnabled()) {
  19975. continue;
  19976. }
  19977. if (light.canAffectMesh(this)) {
  19978. this._lightSources.push(light);
  19979. }
  19980. }
  19981. this._markSubMeshesAsLightDirty();
  19982. };
  19983. /** @hidden */
  19984. AbstractMesh.prototype._resyncLighSource = function (light) {
  19985. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19986. var index = this._lightSources.indexOf(light);
  19987. if (index === -1) {
  19988. if (!isIn) {
  19989. return;
  19990. }
  19991. this._lightSources.push(light);
  19992. }
  19993. else {
  19994. if (isIn) {
  19995. return;
  19996. }
  19997. this._lightSources.splice(index, 1);
  19998. }
  19999. this._markSubMeshesAsLightDirty();
  20000. };
  20001. /** @hidden */
  20002. AbstractMesh.prototype._unBindEffect = function () {
  20003. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20004. var subMesh = _a[_i];
  20005. subMesh.setEffect(null);
  20006. }
  20007. };
  20008. /** @hidden */
  20009. AbstractMesh.prototype._removeLightSource = function (light) {
  20010. var index = this._lightSources.indexOf(light);
  20011. if (index === -1) {
  20012. return;
  20013. }
  20014. this._lightSources.splice(index, 1);
  20015. this._markSubMeshesAsLightDirty();
  20016. };
  20017. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20018. if (!this.subMeshes) {
  20019. return;
  20020. }
  20021. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20022. var subMesh = _a[_i];
  20023. if (subMesh._materialDefines) {
  20024. func(subMesh._materialDefines);
  20025. }
  20026. }
  20027. };
  20028. /** @hidden */
  20029. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20030. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20031. };
  20032. /** @hidden */
  20033. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20034. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20035. };
  20036. /** @hidden */
  20037. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20038. if (!this.subMeshes) {
  20039. return;
  20040. }
  20041. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20042. var subMesh = _a[_i];
  20043. var material = subMesh.getMaterial();
  20044. if (material) {
  20045. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20046. }
  20047. }
  20048. };
  20049. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20050. /**
  20051. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20052. */
  20053. get: function () {
  20054. return this._scaling;
  20055. },
  20056. set: function (newScaling) {
  20057. this._scaling = newScaling;
  20058. if (this.physicsImpostor) {
  20059. this.physicsImpostor.forceUpdate();
  20060. }
  20061. },
  20062. enumerable: true,
  20063. configurable: true
  20064. });
  20065. // Methods
  20066. /**
  20067. * Disables the mesh edge rendering mode
  20068. * @returns the currentAbstractMesh
  20069. */
  20070. AbstractMesh.prototype.disableEdgesRendering = function () {
  20071. if (this._edgesRenderer) {
  20072. this._edgesRenderer.dispose();
  20073. this._edgesRenderer = null;
  20074. }
  20075. return this;
  20076. };
  20077. /**
  20078. * Enables the edge rendering mode on the mesh.
  20079. * This mode makes the mesh edges visible
  20080. * @param epsilon defines the maximal distance between two angles to detect a face
  20081. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20082. * @returns the currentAbstractMesh
  20083. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20084. */
  20085. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20086. if (epsilon === void 0) { epsilon = 0.95; }
  20087. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20088. this.disableEdgesRendering();
  20089. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20090. return this;
  20091. };
  20092. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20093. /**
  20094. * Returns true if the mesh is blocked. Implemented by child classes
  20095. */
  20096. get: function () {
  20097. return false;
  20098. },
  20099. enumerable: true,
  20100. configurable: true
  20101. });
  20102. /**
  20103. * Returns the mesh itself by default. Implemented by child classes
  20104. * @param camera defines the camera to use to pick the right LOD level
  20105. * @returns the currentAbstractMesh
  20106. */
  20107. AbstractMesh.prototype.getLOD = function (camera) {
  20108. return this;
  20109. };
  20110. /**
  20111. * Returns 0 by default. Implemented by child classes
  20112. * @returns an integer
  20113. */
  20114. AbstractMesh.prototype.getTotalVertices = function () {
  20115. return 0;
  20116. };
  20117. /**
  20118. * Returns null by default. Implemented by child classes
  20119. * @returns null
  20120. */
  20121. AbstractMesh.prototype.getIndices = function () {
  20122. return null;
  20123. };
  20124. /**
  20125. * Returns the array of the requested vertex data kind. Implemented by child classes
  20126. * @param kind defines the vertex data kind to use
  20127. * @returns null
  20128. */
  20129. AbstractMesh.prototype.getVerticesData = function (kind) {
  20130. return null;
  20131. };
  20132. /**
  20133. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20134. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20135. * Note that a new underlying VertexBuffer object is created each call.
  20136. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20137. * @param kind defines vertex data kind:
  20138. * * BABYLON.VertexBuffer.PositionKind
  20139. * * BABYLON.VertexBuffer.UVKind
  20140. * * BABYLON.VertexBuffer.UV2Kind
  20141. * * BABYLON.VertexBuffer.UV3Kind
  20142. * * BABYLON.VertexBuffer.UV4Kind
  20143. * * BABYLON.VertexBuffer.UV5Kind
  20144. * * BABYLON.VertexBuffer.UV6Kind
  20145. * * BABYLON.VertexBuffer.ColorKind
  20146. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20147. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20148. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20149. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20150. * @param data defines the data source
  20151. * @param updatable defines if the data must be flagged as updatable (or static)
  20152. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20153. * @returns the current mesh
  20154. */
  20155. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20156. return this;
  20157. };
  20158. /**
  20159. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20160. * If the mesh has no geometry, it is simply returned as it is.
  20161. * @param kind defines vertex data kind:
  20162. * * BABYLON.VertexBuffer.PositionKind
  20163. * * BABYLON.VertexBuffer.UVKind
  20164. * * BABYLON.VertexBuffer.UV2Kind
  20165. * * BABYLON.VertexBuffer.UV3Kind
  20166. * * BABYLON.VertexBuffer.UV4Kind
  20167. * * BABYLON.VertexBuffer.UV5Kind
  20168. * * BABYLON.VertexBuffer.UV6Kind
  20169. * * BABYLON.VertexBuffer.ColorKind
  20170. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20171. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20172. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20173. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20174. * @param data defines the data source
  20175. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20176. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20177. * @returns the current mesh
  20178. */
  20179. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20180. return this;
  20181. };
  20182. /**
  20183. * Sets the mesh indices,
  20184. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20185. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20186. * @param totalVertices Defines the total number of vertices
  20187. * @returns the current mesh
  20188. */
  20189. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20190. return this;
  20191. };
  20192. /**
  20193. * Gets a boolean indicating if specific vertex data is present
  20194. * @param kind defines the vertex data kind to use
  20195. * @returns true is data kind is present
  20196. */
  20197. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20198. return false;
  20199. };
  20200. /**
  20201. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20202. * @returns a BoundingInfo
  20203. */
  20204. AbstractMesh.prototype.getBoundingInfo = function () {
  20205. if (this._masterMesh) {
  20206. return this._masterMesh.getBoundingInfo();
  20207. }
  20208. if (!this._boundingInfo) {
  20209. // this._boundingInfo is being created here
  20210. this._updateBoundingInfo();
  20211. }
  20212. // cannot be null.
  20213. return this._boundingInfo;
  20214. };
  20215. /**
  20216. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20217. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20218. * @returns the current mesh
  20219. */
  20220. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20221. if (includeDescendants === void 0) { includeDescendants = true; }
  20222. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20223. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20224. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20225. if (maxDimension === 0) {
  20226. return this;
  20227. }
  20228. var scale = 1 / maxDimension;
  20229. this.scaling.scaleInPlace(scale);
  20230. return this;
  20231. };
  20232. /**
  20233. * Overwrite the current bounding info
  20234. * @param boundingInfo defines the new bounding info
  20235. * @returns the current mesh
  20236. */
  20237. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20238. this._boundingInfo = boundingInfo;
  20239. return this;
  20240. };
  20241. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20242. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20243. get: function () {
  20244. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20245. },
  20246. enumerable: true,
  20247. configurable: true
  20248. });
  20249. /** @hidden */
  20250. AbstractMesh.prototype._preActivate = function () {
  20251. };
  20252. /** @hidden */
  20253. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20254. };
  20255. /** @hidden */
  20256. AbstractMesh.prototype._activate = function (renderId) {
  20257. this._renderId = renderId;
  20258. };
  20259. /**
  20260. * Gets the current world matrix
  20261. * @returns a Matrix
  20262. */
  20263. AbstractMesh.prototype.getWorldMatrix = function () {
  20264. if (this._masterMesh) {
  20265. return this._masterMesh.getWorldMatrix();
  20266. }
  20267. return _super.prototype.getWorldMatrix.call(this);
  20268. };
  20269. /** @hidden */
  20270. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20271. if (this._masterMesh) {
  20272. return this._masterMesh._getWorldMatrixDeterminant();
  20273. }
  20274. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20275. };
  20276. // ================================== Point of View Movement =================================
  20277. /**
  20278. * Perform relative position change from the point of view of behind the front of the mesh.
  20279. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20280. * Supports definition of mesh facing forward or backward
  20281. * @param amountRight defines the distance on the right axis
  20282. * @param amountUp defines the distance on the up axis
  20283. * @param amountForward defines the distance on the forward axis
  20284. * @returns the current mesh
  20285. */
  20286. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20287. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20288. return this;
  20289. };
  20290. /**
  20291. * Calculate relative position change from the point of view of behind the front of the mesh.
  20292. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20293. * Supports definition of mesh facing forward or backward
  20294. * @param amountRight defines the distance on the right axis
  20295. * @param amountUp defines the distance on the up axis
  20296. * @param amountForward defines the distance on the forward axis
  20297. * @returns the new displacement vector
  20298. */
  20299. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20300. var rotMatrix = new BABYLON.Matrix();
  20301. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20302. rotQuaternion.toRotationMatrix(rotMatrix);
  20303. var translationDelta = BABYLON.Vector3.Zero();
  20304. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20305. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20306. return translationDelta;
  20307. };
  20308. // ================================== Point of View Rotation =================================
  20309. /**
  20310. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20311. * Supports definition of mesh facing forward or backward
  20312. * @param flipBack defines the flip
  20313. * @param twirlClockwise defines the twirl
  20314. * @param tiltRight defines the tilt
  20315. * @returns the current mesh
  20316. */
  20317. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20318. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20319. return this;
  20320. };
  20321. /**
  20322. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20323. * Supports definition of mesh facing forward or backward.
  20324. * @param flipBack defines the flip
  20325. * @param twirlClockwise defines the twirl
  20326. * @param tiltRight defines the tilt
  20327. * @returns the new rotation vector
  20328. */
  20329. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20330. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20331. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20332. };
  20333. /**
  20334. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20335. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20336. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20337. * @returns the new bounding vectors
  20338. */
  20339. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20340. if (includeDescendants === void 0) { includeDescendants = true; }
  20341. if (predicate === void 0) { predicate = null; }
  20342. // Ensures that all world matrix will be recomputed.
  20343. this.getScene().incrementRenderId();
  20344. this.computeWorldMatrix(true);
  20345. var min;
  20346. var max;
  20347. var boundingInfo = this.getBoundingInfo();
  20348. if (!this.subMeshes) {
  20349. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20350. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20351. }
  20352. else {
  20353. min = boundingInfo.boundingBox.minimumWorld;
  20354. max = boundingInfo.boundingBox.maximumWorld;
  20355. }
  20356. if (includeDescendants) {
  20357. var descendants = this.getDescendants(false);
  20358. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20359. var descendant = descendants_1[_i];
  20360. var childMesh = descendant;
  20361. childMesh.computeWorldMatrix(true);
  20362. // Filters meshes based on custom predicate function.
  20363. if (predicate && !predicate(childMesh)) {
  20364. continue;
  20365. }
  20366. //make sure we have the needed params to get mix and max
  20367. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20368. continue;
  20369. }
  20370. var childBoundingInfo = childMesh.getBoundingInfo();
  20371. var boundingBox = childBoundingInfo.boundingBox;
  20372. var minBox = boundingBox.minimumWorld;
  20373. var maxBox = boundingBox.maximumWorld;
  20374. BABYLON.Tools.CheckExtends(minBox, min, max);
  20375. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20376. }
  20377. }
  20378. return {
  20379. min: min,
  20380. max: max
  20381. };
  20382. };
  20383. /** @hidden */
  20384. AbstractMesh.prototype._updateBoundingInfo = function () {
  20385. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20386. this._boundingInfo.update(this.worldMatrixFromCache);
  20387. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20388. return this;
  20389. };
  20390. /** @hidden */
  20391. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20392. if (!this.subMeshes) {
  20393. return this;
  20394. }
  20395. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20396. var subMesh = this.subMeshes[subIndex];
  20397. if (!subMesh.IsGlobal) {
  20398. subMesh.updateBoundingInfo(matrix);
  20399. }
  20400. }
  20401. return this;
  20402. };
  20403. /** @hidden */
  20404. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20405. // Bounding info
  20406. this._updateBoundingInfo();
  20407. };
  20408. /**
  20409. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20410. * A mesh is in the frustum if its bounding box intersects the frustum
  20411. * @param frustumPlanes defines the frustum to test
  20412. * @returns true if the mesh is in the frustum planes
  20413. */
  20414. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20415. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20416. };
  20417. /**
  20418. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20419. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20420. * @param frustumPlanes defines the frustum to test
  20421. * @returns true if the mesh is completely in the frustum planes
  20422. */
  20423. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20424. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20425. };
  20426. /**
  20427. * True if the mesh intersects another mesh or a SolidParticle object
  20428. * @param mesh defines a target mesh or SolidParticle to test
  20429. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20430. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20431. * @returns true if there is an intersection
  20432. */
  20433. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20434. if (precise === void 0) { precise = false; }
  20435. if (!this._boundingInfo || !mesh._boundingInfo) {
  20436. return false;
  20437. }
  20438. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20439. return true;
  20440. }
  20441. if (includeDescendants) {
  20442. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20443. var child = _a[_i];
  20444. if (child.intersectsMesh(mesh, precise, true)) {
  20445. return true;
  20446. }
  20447. }
  20448. }
  20449. return false;
  20450. };
  20451. /**
  20452. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20453. * @param point defines the point to test
  20454. * @returns true if there is an intersection
  20455. */
  20456. AbstractMesh.prototype.intersectsPoint = function (point) {
  20457. if (!this._boundingInfo) {
  20458. return false;
  20459. }
  20460. return this._boundingInfo.intersectsPoint(point);
  20461. };
  20462. /**
  20463. * Gets the current physics impostor
  20464. * @see http://doc.babylonjs.com/features/physics_engine
  20465. * @returns a physics impostor or null
  20466. */
  20467. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20468. return this.physicsImpostor;
  20469. };
  20470. /**
  20471. * Gets the position of the current mesh in camera space
  20472. * @param camera defines the camera to use
  20473. * @returns a position
  20474. */
  20475. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20476. if (camera === void 0) { camera = null; }
  20477. if (!camera) {
  20478. camera = this.getScene().activeCamera;
  20479. }
  20480. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20481. };
  20482. /**
  20483. * Returns the distance from the mesh to the active camera
  20484. * @param camera defines the camera to use
  20485. * @returns the distance
  20486. */
  20487. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20488. if (camera === void 0) { camera = null; }
  20489. if (!camera) {
  20490. camera = this.getScene().activeCamera;
  20491. }
  20492. return this.absolutePosition.subtract(camera.position).length();
  20493. };
  20494. /**
  20495. * Apply a physic impulse to the mesh
  20496. * @param force defines the force to apply
  20497. * @param contactPoint defines where to apply the force
  20498. * @returns the current mesh
  20499. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20500. */
  20501. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20502. if (!this.physicsImpostor) {
  20503. return this;
  20504. }
  20505. this.physicsImpostor.applyImpulse(force, contactPoint);
  20506. return this;
  20507. };
  20508. /**
  20509. * Creates a physic joint between two meshes
  20510. * @param otherMesh defines the other mesh to use
  20511. * @param pivot1 defines the pivot to use on this mesh
  20512. * @param pivot2 defines the pivot to use on the other mesh
  20513. * @param options defines additional options (can be plugin dependent)
  20514. * @returns the current mesh
  20515. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20516. */
  20517. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20518. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20519. return this;
  20520. }
  20521. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20522. mainPivot: pivot1,
  20523. connectedPivot: pivot2,
  20524. nativeParams: options
  20525. });
  20526. return this;
  20527. };
  20528. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20529. // Collisions
  20530. /**
  20531. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20532. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20533. */
  20534. get: function () {
  20535. return this._checkCollisions;
  20536. },
  20537. set: function (collisionEnabled) {
  20538. this._checkCollisions = collisionEnabled;
  20539. if (this.getScene().workerCollisions) {
  20540. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20541. }
  20542. },
  20543. enumerable: true,
  20544. configurable: true
  20545. });
  20546. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20547. /**
  20548. * Gets Collider object used to compute collisions (not physics)
  20549. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20550. */
  20551. get: function () {
  20552. return this._collider;
  20553. },
  20554. enumerable: true,
  20555. configurable: true
  20556. });
  20557. /**
  20558. * Move the mesh using collision engine
  20559. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20560. * @param displacement defines the requested displacement vector
  20561. * @returns the current mesh
  20562. */
  20563. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20564. var globalPosition = this.getAbsolutePosition();
  20565. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20566. if (!this._collider) {
  20567. this._collider = new BABYLON.Collider();
  20568. }
  20569. this._collider._radius = this.ellipsoid;
  20570. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20571. return this;
  20572. };
  20573. // Submeshes octree
  20574. /**
  20575. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20576. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20577. * @param maxCapacity defines the maximum size of each block (64 by default)
  20578. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20579. * @returns the new octree
  20580. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20581. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20582. */
  20583. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20584. if (maxCapacity === void 0) { maxCapacity = 64; }
  20585. if (maxDepth === void 0) { maxDepth = 2; }
  20586. if (!this._submeshesOctree) {
  20587. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20588. }
  20589. this.computeWorldMatrix(true);
  20590. var boundingInfo = this.getBoundingInfo();
  20591. // Update octree
  20592. var bbox = boundingInfo.boundingBox;
  20593. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20594. return this._submeshesOctree;
  20595. };
  20596. // Collisions
  20597. /** @hidden */
  20598. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20599. this._generatePointsArray();
  20600. if (!this._positions) {
  20601. return this;
  20602. }
  20603. // Transformation
  20604. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20605. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20606. subMesh._lastColliderWorldVertices = [];
  20607. subMesh._trianglePlanes = [];
  20608. var start = subMesh.verticesStart;
  20609. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20610. for (var i = start; i < end; i++) {
  20611. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20612. }
  20613. }
  20614. // Collide
  20615. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20616. if (collider.collisionFound) {
  20617. collider.collidedMesh = this;
  20618. }
  20619. return this;
  20620. };
  20621. /** @hidden */
  20622. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20623. var subMeshes;
  20624. var len;
  20625. // Octrees
  20626. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20627. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20628. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20629. len = intersections.length;
  20630. subMeshes = intersections.data;
  20631. }
  20632. else {
  20633. subMeshes = this.subMeshes;
  20634. len = subMeshes.length;
  20635. }
  20636. for (var index = 0; index < len; index++) {
  20637. var subMesh = subMeshes[index];
  20638. // Bounding test
  20639. if (len > 1 && !subMesh._checkCollision(collider))
  20640. continue;
  20641. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20642. }
  20643. return this;
  20644. };
  20645. /** @hidden */
  20646. AbstractMesh.prototype._checkCollision = function (collider) {
  20647. // Bounding box test
  20648. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20649. return this;
  20650. // Transformation matrix
  20651. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20652. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20653. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20654. return this;
  20655. };
  20656. // Picking
  20657. /** @hidden */
  20658. AbstractMesh.prototype._generatePointsArray = function () {
  20659. return false;
  20660. };
  20661. /**
  20662. * Checks if the passed Ray intersects with the mesh
  20663. * @param ray defines the ray to use
  20664. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20665. * @returns the picking info
  20666. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20667. */
  20668. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20669. var pickingInfo = new BABYLON.PickingInfo();
  20670. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20671. return pickingInfo;
  20672. }
  20673. if (!this._generatePointsArray()) {
  20674. return pickingInfo;
  20675. }
  20676. var intersectInfo = null;
  20677. // Octrees
  20678. var subMeshes;
  20679. var len;
  20680. if (this._submeshesOctree && this.useOctreeForPicking) {
  20681. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20682. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20683. len = intersections.length;
  20684. subMeshes = intersections.data;
  20685. }
  20686. else {
  20687. subMeshes = this.subMeshes;
  20688. len = subMeshes.length;
  20689. }
  20690. for (var index = 0; index < len; index++) {
  20691. var subMesh = subMeshes[index];
  20692. // Bounding test
  20693. if (len > 1 && !subMesh.canIntersects(ray))
  20694. continue;
  20695. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20696. if (currentIntersectInfo) {
  20697. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20698. intersectInfo = currentIntersectInfo;
  20699. intersectInfo.subMeshId = index;
  20700. if (fastCheck) {
  20701. break;
  20702. }
  20703. }
  20704. }
  20705. }
  20706. if (intersectInfo) {
  20707. // Get picked point
  20708. var world = this.getWorldMatrix();
  20709. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20710. var direction = ray.direction.clone();
  20711. direction = direction.scale(intersectInfo.distance);
  20712. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20713. var pickedPoint = worldOrigin.add(worldDirection);
  20714. // Return result
  20715. pickingInfo.hit = true;
  20716. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20717. pickingInfo.pickedPoint = pickedPoint;
  20718. pickingInfo.pickedMesh = this;
  20719. pickingInfo.bu = intersectInfo.bu || 0;
  20720. pickingInfo.bv = intersectInfo.bv || 0;
  20721. pickingInfo.faceId = intersectInfo.faceId;
  20722. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20723. return pickingInfo;
  20724. }
  20725. return pickingInfo;
  20726. };
  20727. /**
  20728. * Clones the current mesh
  20729. * @param name defines the mesh name
  20730. * @param newParent defines the new mesh parent
  20731. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20732. * @returns the new mesh
  20733. */
  20734. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20735. return null;
  20736. };
  20737. /**
  20738. * Disposes all the submeshes of the current meshnp
  20739. * @returns the current mesh
  20740. */
  20741. AbstractMesh.prototype.releaseSubMeshes = function () {
  20742. if (this.subMeshes) {
  20743. while (this.subMeshes.length) {
  20744. this.subMeshes[0].dispose();
  20745. }
  20746. }
  20747. else {
  20748. this.subMeshes = new Array();
  20749. }
  20750. return this;
  20751. };
  20752. /**
  20753. * Releases resources associated with this abstract mesh.
  20754. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20755. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20756. */
  20757. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20758. var _this = this;
  20759. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20760. var index;
  20761. // Smart Array Retainers.
  20762. this.getScene().freeActiveMeshes();
  20763. this.getScene().freeRenderingGroups();
  20764. // Action manager
  20765. if (this.actionManager !== undefined && this.actionManager !== null) {
  20766. this.actionManager.dispose();
  20767. this.actionManager = null;
  20768. }
  20769. // Skeleton
  20770. this._skeleton = null;
  20771. // Physics
  20772. if (this.physicsImpostor) {
  20773. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20774. }
  20775. // Intersections in progress
  20776. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20777. var other = this._intersectionsInProgress[index];
  20778. var pos = other._intersectionsInProgress.indexOf(this);
  20779. other._intersectionsInProgress.splice(pos, 1);
  20780. }
  20781. this._intersectionsInProgress = [];
  20782. // Lights
  20783. var lights = this.getScene().lights;
  20784. lights.forEach(function (light) {
  20785. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20786. if (meshIndex !== -1) {
  20787. light.includedOnlyMeshes.splice(meshIndex, 1);
  20788. }
  20789. meshIndex = light.excludedMeshes.indexOf(_this);
  20790. if (meshIndex !== -1) {
  20791. light.excludedMeshes.splice(meshIndex, 1);
  20792. }
  20793. // Shadow generators
  20794. var generator = light.getShadowGenerator();
  20795. if (generator) {
  20796. var shadowMap = generator.getShadowMap();
  20797. if (shadowMap && shadowMap.renderList) {
  20798. meshIndex = shadowMap.renderList.indexOf(_this);
  20799. if (meshIndex !== -1) {
  20800. shadowMap.renderList.splice(meshIndex, 1);
  20801. }
  20802. }
  20803. }
  20804. });
  20805. // Edges
  20806. if (this._edgesRenderer) {
  20807. this._edgesRenderer.dispose();
  20808. this._edgesRenderer = null;
  20809. }
  20810. // SubMeshes
  20811. if (this.getClassName() !== "InstancedMesh") {
  20812. this.releaseSubMeshes();
  20813. }
  20814. // Octree
  20815. var sceneOctree = this.getScene().selectionOctree;
  20816. if (sceneOctree !== undefined && sceneOctree !== null) {
  20817. var index = sceneOctree.dynamicContent.indexOf(this);
  20818. if (index !== -1) {
  20819. sceneOctree.dynamicContent.splice(index, 1);
  20820. }
  20821. }
  20822. // Query
  20823. var engine = this.getScene().getEngine();
  20824. if (this._occlusionQuery) {
  20825. this._isOcclusionQueryInProgress = false;
  20826. engine.deleteQuery(this._occlusionQuery);
  20827. this._occlusionQuery = null;
  20828. }
  20829. // Engine
  20830. engine.wipeCaches();
  20831. // Remove from scene
  20832. this.getScene().removeMesh(this);
  20833. if (disposeMaterialAndTextures) {
  20834. if (this.material) {
  20835. this.material.dispose(false, true);
  20836. }
  20837. }
  20838. if (!doNotRecurse) {
  20839. // Particles
  20840. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20841. if (this.getScene().particleSystems[index].emitter === this) {
  20842. this.getScene().particleSystems[index].dispose();
  20843. index--;
  20844. }
  20845. }
  20846. }
  20847. // facet data
  20848. if (this._facetDataEnabled) {
  20849. this.disableFacetData();
  20850. }
  20851. this.onAfterWorldMatrixUpdateObservable.clear();
  20852. this.onCollideObservable.clear();
  20853. this.onCollisionPositionChangeObservable.clear();
  20854. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20855. };
  20856. /**
  20857. * Adds the passed mesh as a child to the current mesh
  20858. * @param mesh defines the child mesh
  20859. * @returns the current mesh
  20860. */
  20861. AbstractMesh.prototype.addChild = function (mesh) {
  20862. mesh.setParent(this);
  20863. return this;
  20864. };
  20865. /**
  20866. * Removes the passed mesh from the current mesh children list
  20867. * @param mesh defines the child mesh
  20868. * @returns the current mesh
  20869. */
  20870. AbstractMesh.prototype.removeChild = function (mesh) {
  20871. mesh.setParent(null);
  20872. return this;
  20873. };
  20874. // Facet data
  20875. /** @hidden */
  20876. AbstractMesh.prototype._initFacetData = function () {
  20877. if (!this._facetNormals) {
  20878. this._facetNormals = new Array();
  20879. }
  20880. if (!this._facetPositions) {
  20881. this._facetPositions = new Array();
  20882. }
  20883. if (!this._facetPartitioning) {
  20884. this._facetPartitioning = new Array();
  20885. }
  20886. this._facetNb = (this.getIndices().length / 3) | 0;
  20887. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20888. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20889. for (var f = 0; f < this._facetNb; f++) {
  20890. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20891. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20892. }
  20893. this._facetDataEnabled = true;
  20894. return this;
  20895. };
  20896. /**
  20897. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20898. * This method can be called within the render loop.
  20899. * 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
  20900. * @returns the current mesh
  20901. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20902. */
  20903. AbstractMesh.prototype.updateFacetData = function () {
  20904. if (!this._facetDataEnabled) {
  20905. this._initFacetData();
  20906. }
  20907. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20908. var indices = this.getIndices();
  20909. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20910. var bInfo = this.getBoundingInfo();
  20911. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20912. // init arrays, matrix and sort function on first call
  20913. this._facetDepthSortEnabled = true;
  20914. if (indices instanceof Uint16Array) {
  20915. this._depthSortedIndices = new Uint16Array(indices);
  20916. }
  20917. else if (indices instanceof Uint32Array) {
  20918. this._depthSortedIndices = new Uint32Array(indices);
  20919. }
  20920. else {
  20921. var needs32bits = false;
  20922. for (var i = 0; i < indices.length; i++) {
  20923. if (indices[i] > 65535) {
  20924. needs32bits = true;
  20925. break;
  20926. }
  20927. }
  20928. if (needs32bits) {
  20929. this._depthSortedIndices = new Uint32Array(indices);
  20930. }
  20931. else {
  20932. this._depthSortedIndices = new Uint16Array(indices);
  20933. }
  20934. }
  20935. this._facetDepthSortFunction = function (f1, f2) {
  20936. return (f2.sqDistance - f1.sqDistance);
  20937. };
  20938. if (!this._facetDepthSortFrom) {
  20939. var camera = this.getScene().activeCamera;
  20940. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20941. }
  20942. this._depthSortedFacets = [];
  20943. for (var f = 0; f < this._facetNb; f++) {
  20944. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20945. this._depthSortedFacets.push(depthSortedFacet);
  20946. }
  20947. this._invertedMatrix = BABYLON.Matrix.Identity();
  20948. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20949. }
  20950. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20951. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20952. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20953. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20954. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20955. this._subDiv.max = this._partitioningSubdivisions;
  20956. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20957. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20958. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20959. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20960. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20961. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20962. // set the parameters for ComputeNormals()
  20963. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20964. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20965. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20966. this._facetParameters.bInfo = bInfo;
  20967. this._facetParameters.bbSize = this._bbSize;
  20968. this._facetParameters.subDiv = this._subDiv;
  20969. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20970. this._facetParameters.depthSort = this._facetDepthSort;
  20971. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20972. this.computeWorldMatrix(true);
  20973. this._worldMatrix.invertToRef(this._invertedMatrix);
  20974. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20975. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20976. }
  20977. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20978. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20979. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20980. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20981. var l = (this._depthSortedIndices.length / 3) | 0;
  20982. for (var f = 0; f < l; f++) {
  20983. var sind = this._depthSortedFacets[f].ind;
  20984. this._depthSortedIndices[f * 3] = indices[sind];
  20985. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20986. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20987. }
  20988. this.updateIndices(this._depthSortedIndices);
  20989. }
  20990. return this;
  20991. };
  20992. /**
  20993. * Returns the facetLocalNormals array.
  20994. * The normals are expressed in the mesh local spac
  20995. * @returns an array of Vector3
  20996. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20997. */
  20998. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20999. if (!this._facetNormals) {
  21000. this.updateFacetData();
  21001. }
  21002. return this._facetNormals;
  21003. };
  21004. /**
  21005. * Returns the facetLocalPositions array.
  21006. * The facet positions are expressed in the mesh local space
  21007. * @returns an array of Vector3
  21008. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21009. */
  21010. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21011. if (!this._facetPositions) {
  21012. this.updateFacetData();
  21013. }
  21014. return this._facetPositions;
  21015. };
  21016. /**
  21017. * Returns the facetLocalPartioning array
  21018. * @returns an array of array of numbers
  21019. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21020. */
  21021. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21022. if (!this._facetPartitioning) {
  21023. this.updateFacetData();
  21024. }
  21025. return this._facetPartitioning;
  21026. };
  21027. /**
  21028. * Returns the i-th facet position in the world system.
  21029. * This method allocates a new Vector3 per call
  21030. * @param i defines the facet index
  21031. * @returns a new Vector3
  21032. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21033. */
  21034. AbstractMesh.prototype.getFacetPosition = function (i) {
  21035. var pos = BABYLON.Vector3.Zero();
  21036. this.getFacetPositionToRef(i, pos);
  21037. return pos;
  21038. };
  21039. /**
  21040. * Sets the reference Vector3 with the i-th facet position in the world system
  21041. * @param i defines the facet index
  21042. * @param ref defines the target vector
  21043. * @returns the current mesh
  21044. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21045. */
  21046. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21047. var localPos = (this.getFacetLocalPositions())[i];
  21048. var world = this.getWorldMatrix();
  21049. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21050. return this;
  21051. };
  21052. /**
  21053. * Returns the i-th facet normal in the world system.
  21054. * This method allocates a new Vector3 per call
  21055. * @param i defines the facet index
  21056. * @returns a new Vector3
  21057. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21058. */
  21059. AbstractMesh.prototype.getFacetNormal = function (i) {
  21060. var norm = BABYLON.Vector3.Zero();
  21061. this.getFacetNormalToRef(i, norm);
  21062. return norm;
  21063. };
  21064. /**
  21065. * Sets the reference Vector3 with the i-th facet normal in the world system
  21066. * @param i defines the facet index
  21067. * @param ref defines the target vector
  21068. * @returns the current mesh
  21069. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21070. */
  21071. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21072. var localNorm = (this.getFacetLocalNormals())[i];
  21073. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21074. return this;
  21075. };
  21076. /**
  21077. * 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)
  21078. * @param x defines x coordinate
  21079. * @param y defines y coordinate
  21080. * @param z defines z coordinate
  21081. * @returns the array of facet indexes
  21082. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21083. */
  21084. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21085. var bInfo = this.getBoundingInfo();
  21086. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21087. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21088. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21089. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21090. return null;
  21091. }
  21092. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21093. };
  21094. /**
  21095. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21096. * @param projected sets as the (x,y,z) world projection on the facet
  21097. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21098. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21099. * @param x defines x coordinate
  21100. * @param y defines y coordinate
  21101. * @param z defines z coordinate
  21102. * @returns the face index if found (or null instead)
  21103. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21104. */
  21105. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21106. if (checkFace === void 0) { checkFace = false; }
  21107. if (facing === void 0) { facing = true; }
  21108. var world = this.getWorldMatrix();
  21109. var invMat = BABYLON.Tmp.Matrix[5];
  21110. world.invertToRef(invMat);
  21111. var invVect = BABYLON.Tmp.Vector3[8];
  21112. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21113. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21114. if (projected) {
  21115. // tranform the local computed projected vector to world coordinates
  21116. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21117. }
  21118. return closest;
  21119. };
  21120. /**
  21121. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21122. * @param projected sets as the (x,y,z) local projection on the facet
  21123. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21124. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21125. * @param x defines x coordinate
  21126. * @param y defines y coordinate
  21127. * @param z defines z coordinate
  21128. * @returns the face index if found (or null instead)
  21129. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21130. */
  21131. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21132. if (checkFace === void 0) { checkFace = false; }
  21133. if (facing === void 0) { facing = true; }
  21134. var closest = null;
  21135. var tmpx = 0.0;
  21136. var tmpy = 0.0;
  21137. var tmpz = 0.0;
  21138. var d = 0.0; // tmp dot facet normal * facet position
  21139. var t0 = 0.0;
  21140. var projx = 0.0;
  21141. var projy = 0.0;
  21142. var projz = 0.0;
  21143. // Get all the facets in the same partitioning block than (x, y, z)
  21144. var facetPositions = this.getFacetLocalPositions();
  21145. var facetNormals = this.getFacetLocalNormals();
  21146. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21147. if (!facetsInBlock) {
  21148. return null;
  21149. }
  21150. // Get the closest facet to (x, y, z)
  21151. var shortest = Number.MAX_VALUE; // init distance vars
  21152. var tmpDistance = shortest;
  21153. var fib; // current facet in the block
  21154. var norm; // current facet normal
  21155. var p0; // current facet barycenter position
  21156. // loop on all the facets in the current partitioning block
  21157. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21158. fib = facetsInBlock[idx];
  21159. norm = facetNormals[fib];
  21160. p0 = facetPositions[fib];
  21161. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21162. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21163. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21164. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21165. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21166. projx = x + norm.x * t0;
  21167. projy = y + norm.y * t0;
  21168. projz = z + norm.z * t0;
  21169. tmpx = projx - x;
  21170. tmpy = projy - y;
  21171. tmpz = projz - z;
  21172. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21173. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21174. shortest = tmpDistance;
  21175. closest = fib;
  21176. if (projected) {
  21177. projected.x = projx;
  21178. projected.y = projy;
  21179. projected.z = projz;
  21180. }
  21181. }
  21182. }
  21183. }
  21184. return closest;
  21185. };
  21186. /**
  21187. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21188. * @returns the parameters
  21189. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21190. */
  21191. AbstractMesh.prototype.getFacetDataParameters = function () {
  21192. return this._facetParameters;
  21193. };
  21194. /**
  21195. * Disables the feature FacetData and frees the related memory
  21196. * @returns the current mesh
  21197. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21198. */
  21199. AbstractMesh.prototype.disableFacetData = function () {
  21200. if (this._facetDataEnabled) {
  21201. this._facetDataEnabled = false;
  21202. this._facetPositions = new Array();
  21203. this._facetNormals = new Array();
  21204. this._facetPartitioning = new Array();
  21205. this._facetParameters = null;
  21206. this._depthSortedIndices = new Uint32Array(0);
  21207. }
  21208. return this;
  21209. };
  21210. /**
  21211. * Updates the AbstractMesh indices array
  21212. * @param indices defines the data source
  21213. * @returns the current mesh
  21214. */
  21215. AbstractMesh.prototype.updateIndices = function (indices) {
  21216. return this;
  21217. };
  21218. /**
  21219. * Creates new normals data for the mesh
  21220. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21221. * @returns the current mesh
  21222. */
  21223. AbstractMesh.prototype.createNormals = function (updatable) {
  21224. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21225. var indices = this.getIndices();
  21226. var normals;
  21227. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21228. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21229. }
  21230. else {
  21231. normals = [];
  21232. }
  21233. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21234. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21235. return this;
  21236. };
  21237. /**
  21238. * Align the mesh with a normal
  21239. * @param normal defines the normal to use
  21240. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21241. * @returns the current mesh
  21242. */
  21243. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21244. if (!upDirection) {
  21245. upDirection = BABYLON.Axis.Y;
  21246. }
  21247. var axisX = BABYLON.Tmp.Vector3[0];
  21248. var axisZ = BABYLON.Tmp.Vector3[1];
  21249. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21250. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21251. if (this.rotationQuaternion) {
  21252. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21253. }
  21254. else {
  21255. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21256. }
  21257. return this;
  21258. };
  21259. /** @hidden */
  21260. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21261. var engine = this.getEngine();
  21262. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21263. this._isOccluded = false;
  21264. return;
  21265. }
  21266. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21267. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21268. if (isOcclusionQueryAvailable) {
  21269. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21270. this._isOcclusionQueryInProgress = false;
  21271. this._occlusionInternalRetryCounter = 0;
  21272. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21273. }
  21274. else {
  21275. this._occlusionInternalRetryCounter++;
  21276. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21277. this._isOcclusionQueryInProgress = false;
  21278. this._occlusionInternalRetryCounter = 0;
  21279. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21280. // if strict continue the last state of the object.
  21281. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21282. }
  21283. else {
  21284. return;
  21285. }
  21286. }
  21287. }
  21288. var scene = this.getScene();
  21289. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21290. if (!this._occlusionQuery) {
  21291. this._occlusionQuery = engine.createQuery();
  21292. }
  21293. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21294. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21295. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21296. this._isOcclusionQueryInProgress = true;
  21297. };
  21298. /** No occlusion */
  21299. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21300. /** Occlusion set to optimisitic */
  21301. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21302. /** Occlusion set to strict */
  21303. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21304. /** Use an accurante occlusion algorithm */
  21305. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21306. /** Use a conservative occlusion algorithm */
  21307. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21308. return AbstractMesh;
  21309. }(BABYLON.TransformNode));
  21310. BABYLON.AbstractMesh = AbstractMesh;
  21311. })(BABYLON || (BABYLON = {}));
  21312. //# sourceMappingURL=babylon.abstractMesh.js.map
  21313. var BABYLON;
  21314. (function (BABYLON) {
  21315. /**
  21316. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21317. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21318. * 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.
  21319. */
  21320. var Light = /** @class */ (function (_super) {
  21321. __extends(Light, _super);
  21322. /**
  21323. * Creates a Light object in the scene.
  21324. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21325. * @param name The firendly name of the light
  21326. * @param scene The scene the light belongs too
  21327. */
  21328. function Light(name, scene) {
  21329. var _this = _super.call(this, name, scene) || this;
  21330. /**
  21331. * Diffuse gives the basic color to an object.
  21332. */
  21333. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21334. /**
  21335. * Specular produces a highlight color on an object.
  21336. * Note: This is note affecting PBR materials.
  21337. */
  21338. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21339. /**
  21340. * Strength of the light.
  21341. * Note: By default it is define in the framework own unit.
  21342. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21343. */
  21344. _this.intensity = 1.0;
  21345. /**
  21346. * Defines how far from the source the light is impacting in scene units.
  21347. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21348. */
  21349. _this.range = Number.MAX_VALUE;
  21350. /**
  21351. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21352. * of light.
  21353. */
  21354. _this._photometricScale = 1.0;
  21355. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21356. _this._radius = 0.00001;
  21357. /**
  21358. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21359. * exceeding the number allowed of the materials.
  21360. */
  21361. _this.renderPriority = 0;
  21362. _this._shadowEnabled = true;
  21363. _this._excludeWithLayerMask = 0;
  21364. _this._includeOnlyWithLayerMask = 0;
  21365. _this._lightmapMode = 0;
  21366. /**
  21367. * @hidden Internal use only.
  21368. */
  21369. _this._excludedMeshesIds = new Array();
  21370. /**
  21371. * @hidden Internal use only.
  21372. */
  21373. _this._includedOnlyMeshesIds = new Array();
  21374. _this.getScene().addLight(_this);
  21375. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21376. _this._buildUniformLayout();
  21377. _this.includedOnlyMeshes = new Array();
  21378. _this.excludedMeshes = new Array();
  21379. _this._resyncMeshes();
  21380. return _this;
  21381. }
  21382. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21383. /**
  21384. * If every light affecting the material is in this lightmapMode,
  21385. * material.lightmapTexture adds or multiplies
  21386. * (depends on material.useLightmapAsShadowmap)
  21387. * after every other light calculations.
  21388. */
  21389. get: function () {
  21390. return Light._LIGHTMAP_DEFAULT;
  21391. },
  21392. enumerable: true,
  21393. configurable: true
  21394. });
  21395. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21396. /**
  21397. * material.lightmapTexture as only diffuse lighting from this light
  21398. * adds only specular lighting from this light
  21399. * adds dynamic shadows
  21400. */
  21401. get: function () {
  21402. return Light._LIGHTMAP_SPECULAR;
  21403. },
  21404. enumerable: true,
  21405. configurable: true
  21406. });
  21407. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21408. /**
  21409. * material.lightmapTexture as only lighting
  21410. * no light calculation from this light
  21411. * only adds dynamic shadows from this light
  21412. */
  21413. get: function () {
  21414. return Light._LIGHTMAP_SHADOWSONLY;
  21415. },
  21416. enumerable: true,
  21417. configurable: true
  21418. });
  21419. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21420. /**
  21421. * Each light type uses the default quantity according to its type:
  21422. * point/spot lights use luminous intensity
  21423. * directional lights use illuminance
  21424. */
  21425. get: function () {
  21426. return Light._INTENSITYMODE_AUTOMATIC;
  21427. },
  21428. enumerable: true,
  21429. configurable: true
  21430. });
  21431. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21432. /**
  21433. * lumen (lm)
  21434. */
  21435. get: function () {
  21436. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21437. },
  21438. enumerable: true,
  21439. configurable: true
  21440. });
  21441. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21442. /**
  21443. * candela (lm/sr)
  21444. */
  21445. get: function () {
  21446. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21447. },
  21448. enumerable: true,
  21449. configurable: true
  21450. });
  21451. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21452. /**
  21453. * lux (lm/m^2)
  21454. */
  21455. get: function () {
  21456. return Light._INTENSITYMODE_ILLUMINANCE;
  21457. },
  21458. enumerable: true,
  21459. configurable: true
  21460. });
  21461. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21462. /**
  21463. * nit (cd/m^2)
  21464. */
  21465. get: function () {
  21466. return Light._INTENSITYMODE_LUMINANCE;
  21467. },
  21468. enumerable: true,
  21469. configurable: true
  21470. });
  21471. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21472. /**
  21473. * Light type const id of the point light.
  21474. */
  21475. get: function () {
  21476. return Light._LIGHTTYPEID_POINTLIGHT;
  21477. },
  21478. enumerable: true,
  21479. configurable: true
  21480. });
  21481. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21482. /**
  21483. * Light type const id of the directional light.
  21484. */
  21485. get: function () {
  21486. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21487. },
  21488. enumerable: true,
  21489. configurable: true
  21490. });
  21491. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21492. /**
  21493. * Light type const id of the spot light.
  21494. */
  21495. get: function () {
  21496. return Light._LIGHTTYPEID_SPOTLIGHT;
  21497. },
  21498. enumerable: true,
  21499. configurable: true
  21500. });
  21501. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21502. /**
  21503. * Light type const id of the hemispheric light.
  21504. */
  21505. get: function () {
  21506. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21507. },
  21508. enumerable: true,
  21509. configurable: true
  21510. });
  21511. Object.defineProperty(Light.prototype, "intensityMode", {
  21512. /**
  21513. * Gets the photometric scale used to interpret the intensity.
  21514. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21515. */
  21516. get: function () {
  21517. return this._intensityMode;
  21518. },
  21519. /**
  21520. * Sets the photometric scale used to interpret the intensity.
  21521. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21522. */
  21523. set: function (value) {
  21524. this._intensityMode = value;
  21525. this._computePhotometricScale();
  21526. },
  21527. enumerable: true,
  21528. configurable: true
  21529. });
  21530. ;
  21531. ;
  21532. Object.defineProperty(Light.prototype, "radius", {
  21533. /**
  21534. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21535. */
  21536. get: function () {
  21537. return this._radius;
  21538. },
  21539. /**
  21540. * sets the light radius used by PBR Materials to simulate soft area lights.
  21541. */
  21542. set: function (value) {
  21543. this._radius = value;
  21544. this._computePhotometricScale();
  21545. },
  21546. enumerable: true,
  21547. configurable: true
  21548. });
  21549. ;
  21550. ;
  21551. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21552. /**
  21553. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21554. * the current shadow generator.
  21555. */
  21556. get: function () {
  21557. return this._shadowEnabled;
  21558. },
  21559. /**
  21560. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21561. * the current shadow generator.
  21562. */
  21563. set: function (value) {
  21564. if (this._shadowEnabled === value) {
  21565. return;
  21566. }
  21567. this._shadowEnabled = value;
  21568. this._markMeshesAsLightDirty();
  21569. },
  21570. enumerable: true,
  21571. configurable: true
  21572. });
  21573. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21574. /**
  21575. * Gets the only meshes impacted by this light.
  21576. */
  21577. get: function () {
  21578. return this._includedOnlyMeshes;
  21579. },
  21580. /**
  21581. * Sets the only meshes impacted by this light.
  21582. */
  21583. set: function (value) {
  21584. this._includedOnlyMeshes = value;
  21585. this._hookArrayForIncludedOnly(value);
  21586. },
  21587. enumerable: true,
  21588. configurable: true
  21589. });
  21590. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21591. /**
  21592. * Gets the meshes not impacted by this light.
  21593. */
  21594. get: function () {
  21595. return this._excludedMeshes;
  21596. },
  21597. /**
  21598. * Sets the meshes not impacted by this light.
  21599. */
  21600. set: function (value) {
  21601. this._excludedMeshes = value;
  21602. this._hookArrayForExcluded(value);
  21603. },
  21604. enumerable: true,
  21605. configurable: true
  21606. });
  21607. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21608. /**
  21609. * Gets the layer id use to find what meshes are not impacted by the light.
  21610. * Inactive if 0
  21611. */
  21612. get: function () {
  21613. return this._excludeWithLayerMask;
  21614. },
  21615. /**
  21616. * Sets the layer id use to find what meshes are not impacted by the light.
  21617. * Inactive if 0
  21618. */
  21619. set: function (value) {
  21620. this._excludeWithLayerMask = value;
  21621. this._resyncMeshes();
  21622. },
  21623. enumerable: true,
  21624. configurable: true
  21625. });
  21626. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21627. /**
  21628. * Gets the layer id use to find what meshes are impacted by the light.
  21629. * Inactive if 0
  21630. */
  21631. get: function () {
  21632. return this._includeOnlyWithLayerMask;
  21633. },
  21634. /**
  21635. * Sets the layer id use to find what meshes are impacted by the light.
  21636. * Inactive if 0
  21637. */
  21638. set: function (value) {
  21639. this._includeOnlyWithLayerMask = value;
  21640. this._resyncMeshes();
  21641. },
  21642. enumerable: true,
  21643. configurable: true
  21644. });
  21645. Object.defineProperty(Light.prototype, "lightmapMode", {
  21646. /**
  21647. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21648. */
  21649. get: function () {
  21650. return this._lightmapMode;
  21651. },
  21652. /**
  21653. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21654. */
  21655. set: function (value) {
  21656. if (this._lightmapMode === value) {
  21657. return;
  21658. }
  21659. this._lightmapMode = value;
  21660. this._markMeshesAsLightDirty();
  21661. },
  21662. enumerable: true,
  21663. configurable: true
  21664. });
  21665. /**
  21666. * Returns the string "Light".
  21667. * @returns the class name
  21668. */
  21669. Light.prototype.getClassName = function () {
  21670. return "Light";
  21671. };
  21672. /**
  21673. * Converts the light information to a readable string for debug purpose.
  21674. * @param fullDetails Supports for multiple levels of logging within scene loading
  21675. * @returns the human readable light info
  21676. */
  21677. Light.prototype.toString = function (fullDetails) {
  21678. var ret = "Name: " + this.name;
  21679. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21680. if (this.animations) {
  21681. for (var i = 0; i < this.animations.length; i++) {
  21682. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21683. }
  21684. }
  21685. if (fullDetails) {
  21686. }
  21687. return ret;
  21688. };
  21689. /**
  21690. * Set the enabled state of this node.
  21691. * @param value - the new enabled state
  21692. */
  21693. Light.prototype.setEnabled = function (value) {
  21694. _super.prototype.setEnabled.call(this, value);
  21695. this._resyncMeshes();
  21696. };
  21697. /**
  21698. * Returns the Light associated shadow generator if any.
  21699. * @return the associated shadow generator.
  21700. */
  21701. Light.prototype.getShadowGenerator = function () {
  21702. return this._shadowGenerator;
  21703. };
  21704. /**
  21705. * Returns a Vector3, the absolute light position in the World.
  21706. * @returns the world space position of the light
  21707. */
  21708. Light.prototype.getAbsolutePosition = function () {
  21709. return BABYLON.Vector3.Zero();
  21710. };
  21711. /**
  21712. * Specifies if the light will affect the passed mesh.
  21713. * @param mesh The mesh to test against the light
  21714. * @return true the mesh is affected otherwise, false.
  21715. */
  21716. Light.prototype.canAffectMesh = function (mesh) {
  21717. if (!mesh) {
  21718. return true;
  21719. }
  21720. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21721. return false;
  21722. }
  21723. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21724. return false;
  21725. }
  21726. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21727. return false;
  21728. }
  21729. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21730. return false;
  21731. }
  21732. return true;
  21733. };
  21734. /**
  21735. * Computes and Returns the light World matrix.
  21736. * @returns the world matrix
  21737. */
  21738. Light.prototype.getWorldMatrix = function () {
  21739. this._currentRenderId = this.getScene().getRenderId();
  21740. this._childRenderId = this._currentRenderId;
  21741. var worldMatrix = this._getWorldMatrix();
  21742. if (this.parent && this.parent.getWorldMatrix) {
  21743. if (!this._parentedWorldMatrix) {
  21744. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21745. }
  21746. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21747. this._markSyncedWithParent();
  21748. return this._parentedWorldMatrix;
  21749. }
  21750. return worldMatrix;
  21751. };
  21752. /**
  21753. * Sort function to order lights for rendering.
  21754. * @param a First Light object to compare to second.
  21755. * @param b Second Light object to compare first.
  21756. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21757. */
  21758. Light.CompareLightsPriority = function (a, b) {
  21759. //shadow-casting lights have priority over non-shadow-casting lights
  21760. //the renderPrioirty is a secondary sort criterion
  21761. if (a.shadowEnabled !== b.shadowEnabled) {
  21762. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21763. }
  21764. return b.renderPriority - a.renderPriority;
  21765. };
  21766. /**
  21767. * Releases resources associated with this node.
  21768. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21769. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21770. */
  21771. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21772. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21773. if (this._shadowGenerator) {
  21774. this._shadowGenerator.dispose();
  21775. this._shadowGenerator = null;
  21776. }
  21777. // Animations
  21778. this.getScene().stopAnimation(this);
  21779. // Remove from meshes
  21780. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21781. var mesh = _a[_i];
  21782. mesh._removeLightSource(this);
  21783. }
  21784. this._uniformBuffer.dispose();
  21785. // Remove from scene
  21786. this.getScene().removeLight(this);
  21787. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21788. };
  21789. /**
  21790. * Returns the light type ID (integer).
  21791. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21792. */
  21793. Light.prototype.getTypeID = function () {
  21794. return 0;
  21795. };
  21796. /**
  21797. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21798. * @returns the scaled intensity in intensity mode unit
  21799. */
  21800. Light.prototype.getScaledIntensity = function () {
  21801. return this._photometricScale * this.intensity;
  21802. };
  21803. /**
  21804. * Returns a new Light object, named "name", from the current one.
  21805. * @param name The name of the cloned light
  21806. * @returns the new created light
  21807. */
  21808. Light.prototype.clone = function (name) {
  21809. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21810. if (!constructor) {
  21811. return null;
  21812. }
  21813. return BABYLON.SerializationHelper.Clone(constructor, this);
  21814. };
  21815. /**
  21816. * Serializes the current light into a Serialization object.
  21817. * @returns the serialized object.
  21818. */
  21819. Light.prototype.serialize = function () {
  21820. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21821. // Type
  21822. serializationObject.type = this.getTypeID();
  21823. // Parent
  21824. if (this.parent) {
  21825. serializationObject.parentId = this.parent.id;
  21826. }
  21827. // Inclusion / exclusions
  21828. if (this.excludedMeshes.length > 0) {
  21829. serializationObject.excludedMeshesIds = [];
  21830. this.excludedMeshes.forEach(function (mesh) {
  21831. serializationObject.excludedMeshesIds.push(mesh.id);
  21832. });
  21833. }
  21834. if (this.includedOnlyMeshes.length > 0) {
  21835. serializationObject.includedOnlyMeshesIds = [];
  21836. this.includedOnlyMeshes.forEach(function (mesh) {
  21837. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21838. });
  21839. }
  21840. // Animations
  21841. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21842. serializationObject.ranges = this.serializeAnimationRanges();
  21843. return serializationObject;
  21844. };
  21845. /**
  21846. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21847. * This new light is named "name" and added to the passed scene.
  21848. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21849. * @param name The friendly name of the light
  21850. * @param scene The scene the new light will belong to
  21851. * @returns the constructor function
  21852. */
  21853. Light.GetConstructorFromName = function (type, name, scene) {
  21854. switch (type) {
  21855. case 0:
  21856. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21857. case 1:
  21858. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21859. case 2:
  21860. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21861. case 3:
  21862. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21863. }
  21864. return null;
  21865. };
  21866. /**
  21867. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21868. * @param parsedLight The JSON representation of the light
  21869. * @param scene The scene to create the parsed light in
  21870. * @returns the created light after parsing
  21871. */
  21872. Light.Parse = function (parsedLight, scene) {
  21873. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21874. if (!constructor) {
  21875. return null;
  21876. }
  21877. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21878. // Inclusion / exclusions
  21879. if (parsedLight.excludedMeshesIds) {
  21880. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21881. }
  21882. if (parsedLight.includedOnlyMeshesIds) {
  21883. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21884. }
  21885. // Parent
  21886. if (parsedLight.parentId) {
  21887. light._waitingParentId = parsedLight.parentId;
  21888. }
  21889. // Animations
  21890. if (parsedLight.animations) {
  21891. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21892. var parsedAnimation = parsedLight.animations[animationIndex];
  21893. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21894. }
  21895. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21896. }
  21897. if (parsedLight.autoAnimate) {
  21898. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21899. }
  21900. return light;
  21901. };
  21902. Light.prototype._hookArrayForExcluded = function (array) {
  21903. var _this = this;
  21904. var oldPush = array.push;
  21905. array.push = function () {
  21906. var items = [];
  21907. for (var _i = 0; _i < arguments.length; _i++) {
  21908. items[_i] = arguments[_i];
  21909. }
  21910. var result = oldPush.apply(array, items);
  21911. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21912. var item = items_1[_a];
  21913. item._resyncLighSource(_this);
  21914. }
  21915. return result;
  21916. };
  21917. var oldSplice = array.splice;
  21918. array.splice = function (index, deleteCount) {
  21919. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21920. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21921. var item = deleted_1[_i];
  21922. item._resyncLighSource(_this);
  21923. }
  21924. return deleted;
  21925. };
  21926. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21927. var item = array_1[_i];
  21928. item._resyncLighSource(this);
  21929. }
  21930. };
  21931. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21932. var _this = this;
  21933. var oldPush = array.push;
  21934. array.push = function () {
  21935. var items = [];
  21936. for (var _i = 0; _i < arguments.length; _i++) {
  21937. items[_i] = arguments[_i];
  21938. }
  21939. var result = oldPush.apply(array, items);
  21940. _this._resyncMeshes();
  21941. return result;
  21942. };
  21943. var oldSplice = array.splice;
  21944. array.splice = function (index, deleteCount) {
  21945. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21946. _this._resyncMeshes();
  21947. return deleted;
  21948. };
  21949. this._resyncMeshes();
  21950. };
  21951. Light.prototype._resyncMeshes = function () {
  21952. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21953. var mesh = _a[_i];
  21954. mesh._resyncLighSource(this);
  21955. }
  21956. };
  21957. /**
  21958. * Forces the meshes to update their light related information in their rendering used effects
  21959. * @hidden Internal Use Only
  21960. */
  21961. Light.prototype._markMeshesAsLightDirty = function () {
  21962. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21963. var mesh = _a[_i];
  21964. if (mesh._lightSources.indexOf(this) !== -1) {
  21965. mesh._markSubMeshesAsLightDirty();
  21966. }
  21967. }
  21968. };
  21969. /**
  21970. * Recomputes the cached photometric scale if needed.
  21971. */
  21972. Light.prototype._computePhotometricScale = function () {
  21973. this._photometricScale = this._getPhotometricScale();
  21974. this.getScene().resetCachedMaterial();
  21975. };
  21976. /**
  21977. * Returns the Photometric Scale according to the light type and intensity mode.
  21978. */
  21979. Light.prototype._getPhotometricScale = function () {
  21980. var photometricScale = 0.0;
  21981. var lightTypeID = this.getTypeID();
  21982. //get photometric mode
  21983. var photometricMode = this.intensityMode;
  21984. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21985. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21986. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21987. }
  21988. else {
  21989. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21990. }
  21991. }
  21992. //compute photometric scale
  21993. switch (lightTypeID) {
  21994. case Light.LIGHTTYPEID_POINTLIGHT:
  21995. case Light.LIGHTTYPEID_SPOTLIGHT:
  21996. switch (photometricMode) {
  21997. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21998. photometricScale = 1.0 / (4.0 * Math.PI);
  21999. break;
  22000. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22001. photometricScale = 1.0;
  22002. break;
  22003. case Light.INTENSITYMODE_LUMINANCE:
  22004. photometricScale = this.radius * this.radius;
  22005. break;
  22006. }
  22007. break;
  22008. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22009. switch (photometricMode) {
  22010. case Light.INTENSITYMODE_ILLUMINANCE:
  22011. photometricScale = 1.0;
  22012. break;
  22013. case Light.INTENSITYMODE_LUMINANCE:
  22014. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22015. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22016. var apexAngleRadians = this.radius;
  22017. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22018. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22019. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22020. photometricScale = solidAngle;
  22021. break;
  22022. }
  22023. break;
  22024. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22025. // No fall off in hemisperic light.
  22026. photometricScale = 1.0;
  22027. break;
  22028. }
  22029. return photometricScale;
  22030. };
  22031. /**
  22032. * Reorder the light in the scene according to their defined priority.
  22033. * @hidden Internal Use Only
  22034. */
  22035. Light.prototype._reorderLightsInScene = function () {
  22036. var scene = this.getScene();
  22037. if (this._renderPriority != 0) {
  22038. scene.requireLightSorting = true;
  22039. }
  22040. this.getScene().sortLightsByPriority();
  22041. };
  22042. //lightmapMode Consts
  22043. Light._LIGHTMAP_DEFAULT = 0;
  22044. Light._LIGHTMAP_SPECULAR = 1;
  22045. Light._LIGHTMAP_SHADOWSONLY = 2;
  22046. // Intensity Mode Consts
  22047. Light._INTENSITYMODE_AUTOMATIC = 0;
  22048. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22049. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22050. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22051. Light._INTENSITYMODE_LUMINANCE = 4;
  22052. // Light types ids const.
  22053. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22054. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22055. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22056. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22057. __decorate([
  22058. BABYLON.serializeAsColor3()
  22059. ], Light.prototype, "diffuse", void 0);
  22060. __decorate([
  22061. BABYLON.serializeAsColor3()
  22062. ], Light.prototype, "specular", void 0);
  22063. __decorate([
  22064. BABYLON.serialize()
  22065. ], Light.prototype, "intensity", void 0);
  22066. __decorate([
  22067. BABYLON.serialize()
  22068. ], Light.prototype, "range", void 0);
  22069. __decorate([
  22070. BABYLON.serialize()
  22071. ], Light.prototype, "intensityMode", null);
  22072. __decorate([
  22073. BABYLON.serialize()
  22074. ], Light.prototype, "radius", null);
  22075. __decorate([
  22076. BABYLON.serialize()
  22077. ], Light.prototype, "_renderPriority", void 0);
  22078. __decorate([
  22079. BABYLON.expandToProperty("_reorderLightsInScene")
  22080. ], Light.prototype, "renderPriority", void 0);
  22081. __decorate([
  22082. BABYLON.serialize("shadowEnabled")
  22083. ], Light.prototype, "_shadowEnabled", void 0);
  22084. __decorate([
  22085. BABYLON.serialize("excludeWithLayerMask")
  22086. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22087. __decorate([
  22088. BABYLON.serialize("includeOnlyWithLayerMask")
  22089. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22090. __decorate([
  22091. BABYLON.serialize("lightmapMode")
  22092. ], Light.prototype, "_lightmapMode", void 0);
  22093. return Light;
  22094. }(BABYLON.Node));
  22095. BABYLON.Light = Light;
  22096. })(BABYLON || (BABYLON = {}));
  22097. //# sourceMappingURL=babylon.light.js.map
  22098. var BABYLON;
  22099. (function (BABYLON) {
  22100. var Camera = /** @class */ (function (_super) {
  22101. __extends(Camera, _super);
  22102. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22103. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22104. var _this = _super.call(this, name, scene) || this;
  22105. /**
  22106. * The vector the camera should consider as up.
  22107. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22108. */
  22109. _this.upVector = BABYLON.Vector3.Up();
  22110. _this.orthoLeft = null;
  22111. _this.orthoRight = null;
  22112. _this.orthoBottom = null;
  22113. _this.orthoTop = null;
  22114. /**
  22115. * FOV is set in Radians. (default is 0.8)
  22116. */
  22117. _this.fov = 0.8;
  22118. _this.minZ = 1;
  22119. _this.maxZ = 10000.0;
  22120. _this.inertia = 0.9;
  22121. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22122. _this.isIntermediate = false;
  22123. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22124. /**
  22125. * Restricts the camera to viewing objects with the same layerMask.
  22126. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22127. */
  22128. _this.layerMask = 0x0FFFFFFF;
  22129. /**
  22130. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22131. */
  22132. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22133. // Camera rig members
  22134. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22135. _this._rigCameras = new Array();
  22136. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22137. _this._skipRendering = false;
  22138. _this.customRenderTargets = new Array();
  22139. // Observables
  22140. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22141. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22142. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22143. _this.onRestoreStateObservable = new BABYLON.Observable();
  22144. // Cache
  22145. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22146. _this._projectionMatrix = new BABYLON.Matrix();
  22147. _this._doNotComputeProjectionMatrix = false;
  22148. _this._worldMatrix = BABYLON.Matrix.Identity();
  22149. _this._postProcesses = new Array();
  22150. _this._transformMatrix = BABYLON.Matrix.Zero();
  22151. _this._activeMeshes = new BABYLON.SmartArray(256);
  22152. _this._globalPosition = BABYLON.Vector3.Zero();
  22153. _this._refreshFrustumPlanes = true;
  22154. _this.getScene().addCamera(_this);
  22155. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22156. _this.getScene().activeCamera = _this;
  22157. }
  22158. _this.position = position;
  22159. return _this;
  22160. }
  22161. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22162. get: function () {
  22163. return Camera._PERSPECTIVE_CAMERA;
  22164. },
  22165. enumerable: true,
  22166. configurable: true
  22167. });
  22168. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22169. get: function () {
  22170. return Camera._ORTHOGRAPHIC_CAMERA;
  22171. },
  22172. enumerable: true,
  22173. configurable: true
  22174. });
  22175. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22176. /**
  22177. * This is the default FOV mode for perspective cameras.
  22178. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22179. *
  22180. */
  22181. get: function () {
  22182. return Camera._FOVMODE_VERTICAL_FIXED;
  22183. },
  22184. enumerable: true,
  22185. configurable: true
  22186. });
  22187. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22188. /**
  22189. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22190. *
  22191. */
  22192. get: function () {
  22193. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22194. },
  22195. enumerable: true,
  22196. configurable: true
  22197. });
  22198. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22199. get: function () {
  22200. return Camera._RIG_MODE_NONE;
  22201. },
  22202. enumerable: true,
  22203. configurable: true
  22204. });
  22205. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22206. get: function () {
  22207. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22208. },
  22209. enumerable: true,
  22210. configurable: true
  22211. });
  22212. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22213. get: function () {
  22214. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22215. },
  22216. enumerable: true,
  22217. configurable: true
  22218. });
  22219. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22220. get: function () {
  22221. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22222. },
  22223. enumerable: true,
  22224. configurable: true
  22225. });
  22226. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22227. get: function () {
  22228. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22229. },
  22230. enumerable: true,
  22231. configurable: true
  22232. });
  22233. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22234. get: function () {
  22235. return Camera._RIG_MODE_VR;
  22236. },
  22237. enumerable: true,
  22238. configurable: true
  22239. });
  22240. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22241. get: function () {
  22242. return Camera._RIG_MODE_WEBVR;
  22243. },
  22244. enumerable: true,
  22245. configurable: true
  22246. });
  22247. /**
  22248. * Store current camera state (fov, position, etc..)
  22249. */
  22250. Camera.prototype.storeState = function () {
  22251. this._stateStored = true;
  22252. this._storedFov = this.fov;
  22253. return this;
  22254. };
  22255. /**
  22256. * Restores the camera state values if it has been stored. You must call storeState() first
  22257. */
  22258. Camera.prototype._restoreStateValues = function () {
  22259. if (!this._stateStored) {
  22260. return false;
  22261. }
  22262. this.fov = this._storedFov;
  22263. return true;
  22264. };
  22265. /**
  22266. * Restored camera state. You must call storeState() first
  22267. */
  22268. Camera.prototype.restoreState = function () {
  22269. if (this._restoreStateValues()) {
  22270. this.onRestoreStateObservable.notifyObservers(this);
  22271. return true;
  22272. }
  22273. return false;
  22274. };
  22275. Camera.prototype.getClassName = function () {
  22276. return "Camera";
  22277. };
  22278. /**
  22279. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22280. */
  22281. Camera.prototype.toString = function (fullDetails) {
  22282. var ret = "Name: " + this.name;
  22283. ret += ", type: " + this.getClassName();
  22284. if (this.animations) {
  22285. for (var i = 0; i < this.animations.length; i++) {
  22286. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22287. }
  22288. }
  22289. if (fullDetails) {
  22290. }
  22291. return ret;
  22292. };
  22293. Object.defineProperty(Camera.prototype, "globalPosition", {
  22294. get: function () {
  22295. return this._globalPosition;
  22296. },
  22297. enumerable: true,
  22298. configurable: true
  22299. });
  22300. Camera.prototype.getActiveMeshes = function () {
  22301. return this._activeMeshes;
  22302. };
  22303. Camera.prototype.isActiveMesh = function (mesh) {
  22304. return (this._activeMeshes.indexOf(mesh) !== -1);
  22305. };
  22306. /**
  22307. * Is this camera ready to be used/rendered
  22308. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22309. * @return true if the camera is ready
  22310. */
  22311. Camera.prototype.isReady = function (completeCheck) {
  22312. if (completeCheck === void 0) { completeCheck = false; }
  22313. if (completeCheck) {
  22314. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22315. var pp = _a[_i];
  22316. if (pp && !pp.isReady()) {
  22317. return false;
  22318. }
  22319. }
  22320. }
  22321. return _super.prototype.isReady.call(this, completeCheck);
  22322. };
  22323. //Cache
  22324. Camera.prototype._initCache = function () {
  22325. _super.prototype._initCache.call(this);
  22326. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22327. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22328. this._cache.mode = undefined;
  22329. this._cache.minZ = undefined;
  22330. this._cache.maxZ = undefined;
  22331. this._cache.fov = undefined;
  22332. this._cache.fovMode = undefined;
  22333. this._cache.aspectRatio = undefined;
  22334. this._cache.orthoLeft = undefined;
  22335. this._cache.orthoRight = undefined;
  22336. this._cache.orthoBottom = undefined;
  22337. this._cache.orthoTop = undefined;
  22338. this._cache.renderWidth = undefined;
  22339. this._cache.renderHeight = undefined;
  22340. };
  22341. Camera.prototype._updateCache = function (ignoreParentClass) {
  22342. if (!ignoreParentClass) {
  22343. _super.prototype._updateCache.call(this);
  22344. }
  22345. this._cache.position.copyFrom(this.position);
  22346. this._cache.upVector.copyFrom(this.upVector);
  22347. };
  22348. // Synchronized
  22349. Camera.prototype._isSynchronized = function () {
  22350. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22351. };
  22352. Camera.prototype._isSynchronizedViewMatrix = function () {
  22353. if (!_super.prototype._isSynchronized.call(this))
  22354. return false;
  22355. return this._cache.position.equals(this.position)
  22356. && this._cache.upVector.equals(this.upVector)
  22357. && this.isSynchronizedWithParent();
  22358. };
  22359. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22360. var check = this._cache.mode === this.mode
  22361. && this._cache.minZ === this.minZ
  22362. && this._cache.maxZ === this.maxZ;
  22363. if (!check) {
  22364. return false;
  22365. }
  22366. var engine = this.getEngine();
  22367. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22368. check = this._cache.fov === this.fov
  22369. && this._cache.fovMode === this.fovMode
  22370. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22371. }
  22372. else {
  22373. check = this._cache.orthoLeft === this.orthoLeft
  22374. && this._cache.orthoRight === this.orthoRight
  22375. && this._cache.orthoBottom === this.orthoBottom
  22376. && this._cache.orthoTop === this.orthoTop
  22377. && this._cache.renderWidth === engine.getRenderWidth()
  22378. && this._cache.renderHeight === engine.getRenderHeight();
  22379. }
  22380. return check;
  22381. };
  22382. // Controls
  22383. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22384. };
  22385. Camera.prototype.detachControl = function (element) {
  22386. };
  22387. Camera.prototype.update = function () {
  22388. this._checkInputs();
  22389. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22390. this._updateRigCameras();
  22391. }
  22392. };
  22393. Camera.prototype._checkInputs = function () {
  22394. this.onAfterCheckInputsObservable.notifyObservers(this);
  22395. };
  22396. Object.defineProperty(Camera.prototype, "rigCameras", {
  22397. get: function () {
  22398. return this._rigCameras;
  22399. },
  22400. enumerable: true,
  22401. configurable: true
  22402. });
  22403. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22404. get: function () {
  22405. return this._rigPostProcess;
  22406. },
  22407. enumerable: true,
  22408. configurable: true
  22409. });
  22410. /**
  22411. * Internal, gets the first post proces.
  22412. * @returns the first post process to be run on this camera.
  22413. */
  22414. Camera.prototype._getFirstPostProcess = function () {
  22415. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22416. if (this._postProcesses[ppIndex] !== null) {
  22417. return this._postProcesses[ppIndex];
  22418. }
  22419. }
  22420. return null;
  22421. };
  22422. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22423. // invalidate framebuffer
  22424. var firstPostProcess = this._getFirstPostProcess();
  22425. if (firstPostProcess) {
  22426. firstPostProcess.markTextureDirty();
  22427. }
  22428. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22429. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22430. var cam = this._rigCameras[i];
  22431. var rigPostProcess = cam._rigPostProcess;
  22432. // for VR rig, there does not have to be a post process
  22433. if (rigPostProcess) {
  22434. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22435. if (isPass) {
  22436. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22437. cam.isIntermediate = this._postProcesses.length === 0;
  22438. }
  22439. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22440. rigPostProcess.markTextureDirty();
  22441. }
  22442. else {
  22443. cam._postProcesses = this._postProcesses.slice(0);
  22444. }
  22445. }
  22446. };
  22447. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22448. if (insertAt === void 0) { insertAt = null; }
  22449. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22450. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22451. return 0;
  22452. }
  22453. if (insertAt == null || insertAt < 0) {
  22454. this._postProcesses.push(postProcess);
  22455. }
  22456. else if (this._postProcesses[insertAt] === null) {
  22457. this._postProcesses[insertAt] = postProcess;
  22458. }
  22459. else {
  22460. this._postProcesses.splice(insertAt, 0, postProcess);
  22461. }
  22462. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22463. return this._postProcesses.indexOf(postProcess);
  22464. };
  22465. Camera.prototype.detachPostProcess = function (postProcess) {
  22466. var idx = this._postProcesses.indexOf(postProcess);
  22467. if (idx !== -1) {
  22468. this._postProcesses[idx] = null;
  22469. }
  22470. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22471. };
  22472. Camera.prototype.getWorldMatrix = function () {
  22473. if (this._isSynchronizedViewMatrix()) {
  22474. return this._worldMatrix;
  22475. }
  22476. // Getting the the view matrix will also compute the world matrix.
  22477. this.getViewMatrix();
  22478. return this._worldMatrix;
  22479. };
  22480. Camera.prototype._getViewMatrix = function () {
  22481. return BABYLON.Matrix.Identity();
  22482. };
  22483. Camera.prototype.getViewMatrix = function (force) {
  22484. if (!force && this._isSynchronizedViewMatrix()) {
  22485. return this._computedViewMatrix;
  22486. }
  22487. this.updateCache();
  22488. this._computedViewMatrix = this._getViewMatrix();
  22489. this._currentRenderId = this.getScene().getRenderId();
  22490. this._childRenderId = this._currentRenderId;
  22491. this._refreshFrustumPlanes = true;
  22492. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22493. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22494. }
  22495. this.onViewMatrixChangedObservable.notifyObservers(this);
  22496. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22497. return this._computedViewMatrix;
  22498. };
  22499. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22500. this._doNotComputeProjectionMatrix = true;
  22501. if (projection !== undefined) {
  22502. this._projectionMatrix = projection;
  22503. }
  22504. };
  22505. ;
  22506. Camera.prototype.unfreezeProjectionMatrix = function () {
  22507. this._doNotComputeProjectionMatrix = false;
  22508. };
  22509. ;
  22510. Camera.prototype.getProjectionMatrix = function (force) {
  22511. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22512. return this._projectionMatrix;
  22513. }
  22514. // Cache
  22515. this._cache.mode = this.mode;
  22516. this._cache.minZ = this.minZ;
  22517. this._cache.maxZ = this.maxZ;
  22518. // Matrix
  22519. this._refreshFrustumPlanes = true;
  22520. var engine = this.getEngine();
  22521. var scene = this.getScene();
  22522. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22523. this._cache.fov = this.fov;
  22524. this._cache.fovMode = this.fovMode;
  22525. this._cache.aspectRatio = engine.getAspectRatio(this);
  22526. if (this.minZ <= 0) {
  22527. this.minZ = 0.1;
  22528. }
  22529. if (scene.useRightHandedSystem) {
  22530. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22531. }
  22532. else {
  22533. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22534. }
  22535. }
  22536. else {
  22537. var halfWidth = engine.getRenderWidth() / 2.0;
  22538. var halfHeight = engine.getRenderHeight() / 2.0;
  22539. if (scene.useRightHandedSystem) {
  22540. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22541. }
  22542. else {
  22543. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22544. }
  22545. this._cache.orthoLeft = this.orthoLeft;
  22546. this._cache.orthoRight = this.orthoRight;
  22547. this._cache.orthoBottom = this.orthoBottom;
  22548. this._cache.orthoTop = this.orthoTop;
  22549. this._cache.renderWidth = engine.getRenderWidth();
  22550. this._cache.renderHeight = engine.getRenderHeight();
  22551. }
  22552. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22553. return this._projectionMatrix;
  22554. };
  22555. Camera.prototype.getTranformationMatrix = function () {
  22556. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22557. return this._transformMatrix;
  22558. };
  22559. Camera.prototype.updateFrustumPlanes = function () {
  22560. if (!this._refreshFrustumPlanes) {
  22561. return;
  22562. }
  22563. this.getTranformationMatrix();
  22564. if (!this._frustumPlanes) {
  22565. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22566. }
  22567. else {
  22568. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22569. }
  22570. this._refreshFrustumPlanes = false;
  22571. };
  22572. Camera.prototype.isInFrustum = function (target) {
  22573. this.updateFrustumPlanes();
  22574. return target.isInFrustum(this._frustumPlanes);
  22575. };
  22576. Camera.prototype.isCompletelyInFrustum = function (target) {
  22577. this.updateFrustumPlanes();
  22578. return target.isCompletelyInFrustum(this._frustumPlanes);
  22579. };
  22580. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22581. if (length === void 0) { length = 100; }
  22582. if (!transform) {
  22583. transform = this.getWorldMatrix();
  22584. }
  22585. if (!origin) {
  22586. origin = this.position;
  22587. }
  22588. var forward = new BABYLON.Vector3(0, 0, 1);
  22589. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22590. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22591. return new BABYLON.Ray(origin, direction, length);
  22592. };
  22593. /**
  22594. * Releases resources associated with this node.
  22595. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22596. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22597. */
  22598. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22599. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22600. // Observables
  22601. this.onViewMatrixChangedObservable.clear();
  22602. this.onProjectionMatrixChangedObservable.clear();
  22603. this.onAfterCheckInputsObservable.clear();
  22604. this.onRestoreStateObservable.clear();
  22605. // Inputs
  22606. if (this.inputs) {
  22607. this.inputs.clear();
  22608. }
  22609. // Animations
  22610. this.getScene().stopAnimation(this);
  22611. // Remove from scene
  22612. this.getScene().removeCamera(this);
  22613. while (this._rigCameras.length > 0) {
  22614. var camera = this._rigCameras.pop();
  22615. if (camera) {
  22616. camera.dispose();
  22617. }
  22618. }
  22619. // Postprocesses
  22620. if (this._rigPostProcess) {
  22621. this._rigPostProcess.dispose(this);
  22622. this._rigPostProcess = null;
  22623. this._postProcesses = [];
  22624. }
  22625. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22626. this._rigPostProcess = null;
  22627. this._postProcesses = [];
  22628. }
  22629. else {
  22630. var i = this._postProcesses.length;
  22631. while (--i >= 0) {
  22632. var postProcess = this._postProcesses[i];
  22633. if (postProcess) {
  22634. postProcess.dispose(this);
  22635. }
  22636. }
  22637. }
  22638. // Render targets
  22639. var i = this.customRenderTargets.length;
  22640. while (--i >= 0) {
  22641. this.customRenderTargets[i].dispose();
  22642. }
  22643. this.customRenderTargets = [];
  22644. // Active Meshes
  22645. this._activeMeshes.dispose();
  22646. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22647. };
  22648. Object.defineProperty(Camera.prototype, "leftCamera", {
  22649. // ---- Camera rigs section ----
  22650. get: function () {
  22651. if (this._rigCameras.length < 1) {
  22652. return null;
  22653. }
  22654. return this._rigCameras[0];
  22655. },
  22656. enumerable: true,
  22657. configurable: true
  22658. });
  22659. Object.defineProperty(Camera.prototype, "rightCamera", {
  22660. get: function () {
  22661. if (this._rigCameras.length < 2) {
  22662. return null;
  22663. }
  22664. return this._rigCameras[1];
  22665. },
  22666. enumerable: true,
  22667. configurable: true
  22668. });
  22669. Camera.prototype.getLeftTarget = function () {
  22670. if (this._rigCameras.length < 1) {
  22671. return null;
  22672. }
  22673. return this._rigCameras[0].getTarget();
  22674. };
  22675. Camera.prototype.getRightTarget = function () {
  22676. if (this._rigCameras.length < 2) {
  22677. return null;
  22678. }
  22679. return this._rigCameras[1].getTarget();
  22680. };
  22681. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22682. if (this.cameraRigMode === mode) {
  22683. return;
  22684. }
  22685. while (this._rigCameras.length > 0) {
  22686. var camera = this._rigCameras.pop();
  22687. if (camera) {
  22688. camera.dispose();
  22689. }
  22690. }
  22691. this.cameraRigMode = mode;
  22692. this._cameraRigParams = {};
  22693. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22694. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22695. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22696. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22697. // create the rig cameras, unless none
  22698. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22699. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22700. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22701. if (leftCamera && rightCamera) {
  22702. this._rigCameras.push(leftCamera);
  22703. this._rigCameras.push(rightCamera);
  22704. }
  22705. }
  22706. switch (this.cameraRigMode) {
  22707. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22708. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22709. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22710. break;
  22711. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22712. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22713. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22714. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22715. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22716. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22717. break;
  22718. case Camera.RIG_MODE_VR:
  22719. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22720. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22721. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22722. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22723. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22724. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22725. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22726. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22727. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22728. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22729. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22730. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22731. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22732. if (metrics.compensateDistortion) {
  22733. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22734. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22735. }
  22736. break;
  22737. case Camera.RIG_MODE_WEBVR:
  22738. if (rigParams.vrDisplay) {
  22739. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22740. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22741. //Left eye
  22742. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22743. this._rigCameras[0].setCameraRigParameter("left", true);
  22744. //leaving this for future reference
  22745. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22746. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22747. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22748. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22749. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22750. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22751. this._rigCameras[0].parent = this;
  22752. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22753. //Right eye
  22754. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22755. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22756. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22757. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22758. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22759. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22760. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22761. this._rigCameras[1].parent = this;
  22762. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22763. if (Camera.UseAlternateWebVRRendering) {
  22764. this._rigCameras[1]._skipRendering = true;
  22765. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22766. }
  22767. }
  22768. break;
  22769. }
  22770. this._cascadePostProcessesToRigCams();
  22771. this.update();
  22772. };
  22773. Camera.prototype._getVRProjectionMatrix = function () {
  22774. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22775. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22776. return this._projectionMatrix;
  22777. };
  22778. Camera.prototype._updateCameraRotationMatrix = function () {
  22779. //Here for WebVR
  22780. };
  22781. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22782. //Here for WebVR
  22783. };
  22784. /**
  22785. * This function MUST be overwritten by the different WebVR cameras available.
  22786. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22787. */
  22788. Camera.prototype._getWebVRProjectionMatrix = function () {
  22789. return BABYLON.Matrix.Identity();
  22790. };
  22791. /**
  22792. * This function MUST be overwritten by the different WebVR cameras available.
  22793. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22794. */
  22795. Camera.prototype._getWebVRViewMatrix = function () {
  22796. return BABYLON.Matrix.Identity();
  22797. };
  22798. Camera.prototype.setCameraRigParameter = function (name, value) {
  22799. if (!this._cameraRigParams) {
  22800. this._cameraRigParams = {};
  22801. }
  22802. this._cameraRigParams[name] = value;
  22803. //provisionnally:
  22804. if (name === "interaxialDistance") {
  22805. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22806. }
  22807. };
  22808. /**
  22809. * needs to be overridden by children so sub has required properties to be copied
  22810. */
  22811. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22812. return null;
  22813. };
  22814. /**
  22815. * May need to be overridden by children
  22816. */
  22817. Camera.prototype._updateRigCameras = function () {
  22818. for (var i = 0; i < this._rigCameras.length; i++) {
  22819. this._rigCameras[i].minZ = this.minZ;
  22820. this._rigCameras[i].maxZ = this.maxZ;
  22821. this._rigCameras[i].fov = this.fov;
  22822. }
  22823. // only update viewport when ANAGLYPH
  22824. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22825. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22826. }
  22827. };
  22828. Camera.prototype._setupInputs = function () {
  22829. };
  22830. Camera.prototype.serialize = function () {
  22831. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22832. // Type
  22833. serializationObject.type = this.getClassName();
  22834. // Parent
  22835. if (this.parent) {
  22836. serializationObject.parentId = this.parent.id;
  22837. }
  22838. if (this.inputs) {
  22839. this.inputs.serialize(serializationObject);
  22840. }
  22841. // Animations
  22842. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22843. serializationObject.ranges = this.serializeAnimationRanges();
  22844. return serializationObject;
  22845. };
  22846. Camera.prototype.clone = function (name) {
  22847. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22848. };
  22849. Camera.prototype.getDirection = function (localAxis) {
  22850. var result = BABYLON.Vector3.Zero();
  22851. this.getDirectionToRef(localAxis, result);
  22852. return result;
  22853. };
  22854. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22855. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22856. };
  22857. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22858. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22859. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22860. switch (type) {
  22861. case "ArcRotateCamera":
  22862. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22863. case "DeviceOrientationCamera":
  22864. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22865. case "FollowCamera":
  22866. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22867. case "ArcFollowCamera":
  22868. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22869. case "GamepadCamera":
  22870. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22871. case "TouchCamera":
  22872. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22873. case "VirtualJoysticksCamera":
  22874. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22875. case "WebVRFreeCamera":
  22876. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22877. case "WebVRGamepadCamera":
  22878. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22879. case "VRDeviceOrientationFreeCamera":
  22880. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22881. case "VRDeviceOrientationGamepadCamera":
  22882. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22883. case "AnaglyphArcRotateCamera":
  22884. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22885. case "AnaglyphFreeCamera":
  22886. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22887. case "AnaglyphGamepadCamera":
  22888. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22889. case "AnaglyphUniversalCamera":
  22890. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22891. case "StereoscopicArcRotateCamera":
  22892. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22893. case "StereoscopicFreeCamera":
  22894. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22895. case "StereoscopicGamepadCamera":
  22896. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22897. case "StereoscopicUniversalCamera":
  22898. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22899. case "FreeCamera": // Forcing Universal here
  22900. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22901. default: // Universal Camera is the default value
  22902. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22903. }
  22904. };
  22905. Camera.prototype.computeWorldMatrix = function () {
  22906. return this.getWorldMatrix();
  22907. };
  22908. Camera.Parse = function (parsedCamera, scene) {
  22909. var type = parsedCamera.type;
  22910. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22911. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22912. // Parent
  22913. if (parsedCamera.parentId) {
  22914. camera._waitingParentId = parsedCamera.parentId;
  22915. }
  22916. //If camera has an input manager, let it parse inputs settings
  22917. if (camera.inputs) {
  22918. camera.inputs.parse(parsedCamera);
  22919. camera._setupInputs();
  22920. }
  22921. if (camera.setPosition) { // need to force position
  22922. camera.position.copyFromFloats(0, 0, 0);
  22923. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22924. }
  22925. // Target
  22926. if (parsedCamera.target) {
  22927. if (camera.setTarget) {
  22928. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22929. }
  22930. }
  22931. // Apply 3d rig, when found
  22932. if (parsedCamera.cameraRigMode) {
  22933. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22934. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22935. }
  22936. // Animations
  22937. if (parsedCamera.animations) {
  22938. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22939. var parsedAnimation = parsedCamera.animations[animationIndex];
  22940. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22941. }
  22942. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22943. }
  22944. if (parsedCamera.autoAnimate) {
  22945. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22946. }
  22947. return camera;
  22948. };
  22949. // Statics
  22950. Camera._PERSPECTIVE_CAMERA = 0;
  22951. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22952. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22953. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22954. Camera._RIG_MODE_NONE = 0;
  22955. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22956. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22957. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22958. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22959. Camera._RIG_MODE_VR = 20;
  22960. Camera._RIG_MODE_WEBVR = 21;
  22961. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22962. Camera.UseAlternateWebVRRendering = false;
  22963. __decorate([
  22964. BABYLON.serializeAsVector3()
  22965. ], Camera.prototype, "position", void 0);
  22966. __decorate([
  22967. BABYLON.serializeAsVector3()
  22968. ], Camera.prototype, "upVector", void 0);
  22969. __decorate([
  22970. BABYLON.serialize()
  22971. ], Camera.prototype, "orthoLeft", void 0);
  22972. __decorate([
  22973. BABYLON.serialize()
  22974. ], Camera.prototype, "orthoRight", void 0);
  22975. __decorate([
  22976. BABYLON.serialize()
  22977. ], Camera.prototype, "orthoBottom", void 0);
  22978. __decorate([
  22979. BABYLON.serialize()
  22980. ], Camera.prototype, "orthoTop", void 0);
  22981. __decorate([
  22982. BABYLON.serialize()
  22983. ], Camera.prototype, "fov", void 0);
  22984. __decorate([
  22985. BABYLON.serialize()
  22986. ], Camera.prototype, "minZ", void 0);
  22987. __decorate([
  22988. BABYLON.serialize()
  22989. ], Camera.prototype, "maxZ", void 0);
  22990. __decorate([
  22991. BABYLON.serialize()
  22992. ], Camera.prototype, "inertia", void 0);
  22993. __decorate([
  22994. BABYLON.serialize()
  22995. ], Camera.prototype, "mode", void 0);
  22996. __decorate([
  22997. BABYLON.serialize()
  22998. ], Camera.prototype, "layerMask", void 0);
  22999. __decorate([
  23000. BABYLON.serialize()
  23001. ], Camera.prototype, "fovMode", void 0);
  23002. __decorate([
  23003. BABYLON.serialize()
  23004. ], Camera.prototype, "cameraRigMode", void 0);
  23005. __decorate([
  23006. BABYLON.serialize()
  23007. ], Camera.prototype, "interaxialDistance", void 0);
  23008. __decorate([
  23009. BABYLON.serialize()
  23010. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23011. return Camera;
  23012. }(BABYLON.Node));
  23013. BABYLON.Camera = Camera;
  23014. })(BABYLON || (BABYLON = {}));
  23015. //# sourceMappingURL=babylon.camera.js.map
  23016. var BABYLON;
  23017. (function (BABYLON) {
  23018. var RenderingManager = /** @class */ (function () {
  23019. function RenderingManager(scene) {
  23020. this._renderingGroups = new Array();
  23021. this._autoClearDepthStencil = {};
  23022. this._customOpaqueSortCompareFn = {};
  23023. this._customAlphaTestSortCompareFn = {};
  23024. this._customTransparentSortCompareFn = {};
  23025. this._renderinGroupInfo = null;
  23026. this._scene = scene;
  23027. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23028. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23029. }
  23030. }
  23031. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23032. if (depth === void 0) { depth = true; }
  23033. if (stencil === void 0) { stencil = true; }
  23034. if (this._depthStencilBufferAlreadyCleaned) {
  23035. return;
  23036. }
  23037. this._scene.getEngine().clear(null, false, depth, stencil);
  23038. this._depthStencilBufferAlreadyCleaned = true;
  23039. };
  23040. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23041. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23042. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23043. var info = null;
  23044. if (observable) {
  23045. if (!this._renderinGroupInfo) {
  23046. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23047. }
  23048. info = this._renderinGroupInfo;
  23049. info.scene = this._scene;
  23050. info.camera = this._scene.activeCamera;
  23051. }
  23052. // Dispatch sprites
  23053. if (renderSprites) {
  23054. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23055. var manager = this._scene.spriteManagers[index];
  23056. this.dispatchSprites(manager);
  23057. }
  23058. }
  23059. // Render
  23060. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23061. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23062. var renderingGroup = this._renderingGroups[index];
  23063. if (!renderingGroup && !observable)
  23064. continue;
  23065. var renderingGroupMask = 0;
  23066. // Fire PRECLEAR stage
  23067. if (observable && info) {
  23068. renderingGroupMask = Math.pow(2, index);
  23069. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23070. info.renderingGroupId = index;
  23071. observable.notifyObservers(info, renderingGroupMask);
  23072. }
  23073. // Clear depth/stencil if needed
  23074. if (RenderingManager.AUTOCLEAR) {
  23075. var autoClear = this._autoClearDepthStencil[index];
  23076. if (autoClear && autoClear.autoClear) {
  23077. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23078. }
  23079. }
  23080. if (observable && info) {
  23081. // Fire PREOPAQUE stage
  23082. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23083. observable.notifyObservers(info, renderingGroupMask);
  23084. // Fire PRETRANSPARENT stage
  23085. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23086. observable.notifyObservers(info, renderingGroupMask);
  23087. }
  23088. if (renderingGroup)
  23089. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23090. // Fire POSTTRANSPARENT stage
  23091. if (observable && info) {
  23092. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23093. observable.notifyObservers(info, renderingGroupMask);
  23094. }
  23095. }
  23096. };
  23097. RenderingManager.prototype.reset = function () {
  23098. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23099. var renderingGroup = this._renderingGroups[index];
  23100. if (renderingGroup) {
  23101. renderingGroup.prepare();
  23102. }
  23103. }
  23104. };
  23105. RenderingManager.prototype.dispose = function () {
  23106. this.freeRenderingGroups();
  23107. this._renderingGroups.length = 0;
  23108. };
  23109. /**
  23110. * Clear the info related to rendering groups preventing retention points during dispose.
  23111. */
  23112. RenderingManager.prototype.freeRenderingGroups = function () {
  23113. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23114. var renderingGroup = this._renderingGroups[index];
  23115. if (renderingGroup) {
  23116. renderingGroup.dispose();
  23117. }
  23118. }
  23119. };
  23120. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23121. if (this._renderingGroups[renderingGroupId] === undefined) {
  23122. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23123. }
  23124. };
  23125. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23126. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23127. this._prepareRenderingGroup(renderingGroupId);
  23128. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23129. };
  23130. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23131. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23132. this._prepareRenderingGroup(renderingGroupId);
  23133. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23134. };
  23135. /**
  23136. * @param subMesh The submesh to dispatch
  23137. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23138. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23139. */
  23140. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23141. if (mesh === undefined) {
  23142. mesh = subMesh.getMesh();
  23143. }
  23144. var renderingGroupId = mesh.renderingGroupId || 0;
  23145. this._prepareRenderingGroup(renderingGroupId);
  23146. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23147. };
  23148. /**
  23149. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23150. * This allowed control for front to back rendering or reversly depending of the special needs.
  23151. *
  23152. * @param renderingGroupId The rendering group id corresponding to its index
  23153. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23154. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23155. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23156. */
  23157. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23158. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23159. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23160. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23161. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23162. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23163. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23164. if (this._renderingGroups[renderingGroupId]) {
  23165. var group = this._renderingGroups[renderingGroupId];
  23166. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23167. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23168. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23169. }
  23170. };
  23171. /**
  23172. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23173. *
  23174. * @param renderingGroupId The rendering group id corresponding to its index
  23175. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23176. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23177. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23178. */
  23179. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23180. if (depth === void 0) { depth = true; }
  23181. if (stencil === void 0) { stencil = true; }
  23182. this._autoClearDepthStencil[renderingGroupId] = {
  23183. autoClear: autoClearDepthStencil,
  23184. depth: depth,
  23185. stencil: stencil
  23186. };
  23187. };
  23188. /**
  23189. * The max id used for rendering groups (not included)
  23190. */
  23191. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23192. /**
  23193. * The min id used for rendering groups (included)
  23194. */
  23195. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23196. /**
  23197. * Used to globally prevent autoclearing scenes.
  23198. */
  23199. RenderingManager.AUTOCLEAR = true;
  23200. return RenderingManager;
  23201. }());
  23202. BABYLON.RenderingManager = RenderingManager;
  23203. })(BABYLON || (BABYLON = {}));
  23204. //# sourceMappingURL=babylon.renderingManager.js.map
  23205. var BABYLON;
  23206. (function (BABYLON) {
  23207. var RenderingGroup = /** @class */ (function () {
  23208. /**
  23209. * Creates a new rendering group.
  23210. * @param index The rendering group index
  23211. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23212. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23213. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23214. */
  23215. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23216. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23217. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23218. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23219. this.index = index;
  23220. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23221. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23222. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23223. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23224. this._particleSystems = new BABYLON.SmartArray(256);
  23225. this._spriteManagers = new BABYLON.SmartArray(256);
  23226. this._edgesRenderers = new BABYLON.SmartArray(16);
  23227. this._scene = scene;
  23228. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23229. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23230. this.transparentSortCompareFn = transparentSortCompareFn;
  23231. }
  23232. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23233. /**
  23234. * Set the opaque sort comparison function.
  23235. * If null the sub meshes will be render in the order they were created
  23236. */
  23237. set: function (value) {
  23238. this._opaqueSortCompareFn = value;
  23239. if (value) {
  23240. this._renderOpaque = this.renderOpaqueSorted;
  23241. }
  23242. else {
  23243. this._renderOpaque = RenderingGroup.renderUnsorted;
  23244. }
  23245. },
  23246. enumerable: true,
  23247. configurable: true
  23248. });
  23249. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23250. /**
  23251. * Set the alpha test sort comparison function.
  23252. * If null the sub meshes will be render in the order they were created
  23253. */
  23254. set: function (value) {
  23255. this._alphaTestSortCompareFn = value;
  23256. if (value) {
  23257. this._renderAlphaTest = this.renderAlphaTestSorted;
  23258. }
  23259. else {
  23260. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23261. }
  23262. },
  23263. enumerable: true,
  23264. configurable: true
  23265. });
  23266. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23267. /**
  23268. * Set the transparent sort comparison function.
  23269. * If null the sub meshes will be render in the order they were created
  23270. */
  23271. set: function (value) {
  23272. if (value) {
  23273. this._transparentSortCompareFn = value;
  23274. }
  23275. else {
  23276. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23277. }
  23278. this._renderTransparent = this.renderTransparentSorted;
  23279. },
  23280. enumerable: true,
  23281. configurable: true
  23282. });
  23283. /**
  23284. * Render all the sub meshes contained in the group.
  23285. * @param customRenderFunction Used to override the default render behaviour of the group.
  23286. * @returns true if rendered some submeshes.
  23287. */
  23288. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23289. if (customRenderFunction) {
  23290. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23291. return;
  23292. }
  23293. var engine = this._scene.getEngine();
  23294. // Depth only
  23295. if (this._depthOnlySubMeshes.length !== 0) {
  23296. engine.setColorWrite(false);
  23297. this._renderAlphaTest(this._depthOnlySubMeshes);
  23298. engine.setColorWrite(true);
  23299. }
  23300. // Opaque
  23301. if (this._opaqueSubMeshes.length !== 0) {
  23302. this._renderOpaque(this._opaqueSubMeshes);
  23303. }
  23304. // Alpha test
  23305. if (this._alphaTestSubMeshes.length !== 0) {
  23306. this._renderAlphaTest(this._alphaTestSubMeshes);
  23307. }
  23308. var stencilState = engine.getStencilBuffer();
  23309. engine.setStencilBuffer(false);
  23310. // Sprites
  23311. if (renderSprites) {
  23312. this._renderSprites();
  23313. }
  23314. // Particles
  23315. if (renderParticles) {
  23316. this._renderParticles(activeMeshes);
  23317. }
  23318. if (this.onBeforeTransparentRendering) {
  23319. this.onBeforeTransparentRendering();
  23320. }
  23321. // Transparent
  23322. if (this._transparentSubMeshes.length !== 0) {
  23323. this._renderTransparent(this._transparentSubMeshes);
  23324. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23325. }
  23326. // Set back stencil to false in case it changes before the edge renderer.
  23327. engine.setStencilBuffer(false);
  23328. // Edges
  23329. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23330. this._edgesRenderers.data[edgesRendererIndex].render();
  23331. }
  23332. // Restore Stencil state.
  23333. engine.setStencilBuffer(stencilState);
  23334. };
  23335. /**
  23336. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23337. * @param subMeshes The submeshes to render
  23338. */
  23339. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23340. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23341. };
  23342. /**
  23343. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23344. * @param subMeshes The submeshes to render
  23345. */
  23346. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23347. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23348. };
  23349. /**
  23350. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23351. * @param subMeshes The submeshes to render
  23352. */
  23353. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23354. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23355. };
  23356. /**
  23357. * Renders the submeshes in a specified order.
  23358. * @param subMeshes The submeshes to sort before render
  23359. * @param sortCompareFn The comparison function use to sort
  23360. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23361. * @param transparent Specifies to activate blending if true
  23362. */
  23363. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23364. var subIndex = 0;
  23365. var subMesh;
  23366. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23367. for (; subIndex < subMeshes.length; subIndex++) {
  23368. subMesh = subMeshes.data[subIndex];
  23369. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23370. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23371. }
  23372. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23373. if (sortCompareFn) {
  23374. sortedArray.sort(sortCompareFn);
  23375. }
  23376. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23377. subMesh = sortedArray[subIndex];
  23378. if (transparent) {
  23379. var material = subMesh.getMaterial();
  23380. if (material && material.needDepthPrePass) {
  23381. var engine = material.getScene().getEngine();
  23382. engine.setColorWrite(false);
  23383. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23384. subMesh.render(false);
  23385. engine.setColorWrite(true);
  23386. }
  23387. }
  23388. subMesh.render(transparent);
  23389. }
  23390. };
  23391. /**
  23392. * Renders the submeshes in the order they were dispatched (no sort applied).
  23393. * @param subMeshes The submeshes to render
  23394. */
  23395. RenderingGroup.renderUnsorted = function (subMeshes) {
  23396. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23397. var submesh = subMeshes.data[subIndex];
  23398. submesh.render(false);
  23399. }
  23400. };
  23401. /**
  23402. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23403. * are rendered back to front if in the same alpha index.
  23404. *
  23405. * @param a The first submesh
  23406. * @param b The second submesh
  23407. * @returns The result of the comparison
  23408. */
  23409. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23410. // Alpha index first
  23411. if (a._alphaIndex > b._alphaIndex) {
  23412. return 1;
  23413. }
  23414. if (a._alphaIndex < b._alphaIndex) {
  23415. return -1;
  23416. }
  23417. // Then distance to camera
  23418. return RenderingGroup.backToFrontSortCompare(a, b);
  23419. };
  23420. /**
  23421. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23422. * are rendered back to front.
  23423. *
  23424. * @param a The first submesh
  23425. * @param b The second submesh
  23426. * @returns The result of the comparison
  23427. */
  23428. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23429. // Then distance to camera
  23430. if (a._distanceToCamera < b._distanceToCamera) {
  23431. return 1;
  23432. }
  23433. if (a._distanceToCamera > b._distanceToCamera) {
  23434. return -1;
  23435. }
  23436. return 0;
  23437. };
  23438. /**
  23439. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23440. * are rendered front to back (prevent overdraw).
  23441. *
  23442. * @param a The first submesh
  23443. * @param b The second submesh
  23444. * @returns The result of the comparison
  23445. */
  23446. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23447. // Then distance to camera
  23448. if (a._distanceToCamera < b._distanceToCamera) {
  23449. return -1;
  23450. }
  23451. if (a._distanceToCamera > b._distanceToCamera) {
  23452. return 1;
  23453. }
  23454. return 0;
  23455. };
  23456. /**
  23457. * Resets the different lists of submeshes to prepare a new frame.
  23458. */
  23459. RenderingGroup.prototype.prepare = function () {
  23460. this._opaqueSubMeshes.reset();
  23461. this._transparentSubMeshes.reset();
  23462. this._alphaTestSubMeshes.reset();
  23463. this._depthOnlySubMeshes.reset();
  23464. this._particleSystems.reset();
  23465. this._spriteManagers.reset();
  23466. this._edgesRenderers.reset();
  23467. };
  23468. RenderingGroup.prototype.dispose = function () {
  23469. this._opaqueSubMeshes.dispose();
  23470. this._transparentSubMeshes.dispose();
  23471. this._alphaTestSubMeshes.dispose();
  23472. this._depthOnlySubMeshes.dispose();
  23473. this._particleSystems.dispose();
  23474. this._spriteManagers.dispose();
  23475. this._edgesRenderers.dispose();
  23476. };
  23477. /**
  23478. * Inserts the submesh in its correct queue depending on its material.
  23479. * @param subMesh The submesh to dispatch
  23480. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23481. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23482. */
  23483. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23484. // Get mesh and materials if not provided
  23485. if (mesh === undefined) {
  23486. mesh = subMesh.getMesh();
  23487. }
  23488. if (material === undefined) {
  23489. material = subMesh.getMaterial();
  23490. }
  23491. if (material === null || material === undefined) {
  23492. return;
  23493. }
  23494. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23495. this._transparentSubMeshes.push(subMesh);
  23496. }
  23497. else if (material.needAlphaTesting()) { // Alpha test
  23498. if (material.needDepthPrePass) {
  23499. this._depthOnlySubMeshes.push(subMesh);
  23500. }
  23501. this._alphaTestSubMeshes.push(subMesh);
  23502. }
  23503. else {
  23504. if (material.needDepthPrePass) {
  23505. this._depthOnlySubMeshes.push(subMesh);
  23506. }
  23507. this._opaqueSubMeshes.push(subMesh); // Opaque
  23508. }
  23509. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23510. this._edgesRenderers.push(mesh._edgesRenderer);
  23511. }
  23512. };
  23513. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23514. this._spriteManagers.push(spriteManager);
  23515. };
  23516. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23517. this._particleSystems.push(particleSystem);
  23518. };
  23519. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23520. if (this._particleSystems.length === 0) {
  23521. return;
  23522. }
  23523. // Particles
  23524. var activeCamera = this._scene.activeCamera;
  23525. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23526. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23527. var particleSystem = this._particleSystems.data[particleIndex];
  23528. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23529. continue;
  23530. }
  23531. var emitter = particleSystem.emitter;
  23532. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23533. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23534. }
  23535. }
  23536. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23537. };
  23538. RenderingGroup.prototype._renderSprites = function () {
  23539. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23540. return;
  23541. }
  23542. // Sprites
  23543. var activeCamera = this._scene.activeCamera;
  23544. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23545. for (var id = 0; id < this._spriteManagers.length; id++) {
  23546. var spriteManager = this._spriteManagers.data[id];
  23547. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23548. spriteManager.render();
  23549. }
  23550. }
  23551. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23552. };
  23553. return RenderingGroup;
  23554. }());
  23555. BABYLON.RenderingGroup = RenderingGroup;
  23556. })(BABYLON || (BABYLON = {}));
  23557. //# sourceMappingURL=babylon.renderingGroup.js.map
  23558. var BABYLON;
  23559. (function (BABYLON) {
  23560. /** @hidden */
  23561. var ClickInfo = /** @class */ (function () {
  23562. function ClickInfo() {
  23563. this._singleClick = false;
  23564. this._doubleClick = false;
  23565. this._hasSwiped = false;
  23566. this._ignore = false;
  23567. }
  23568. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23569. get: function () {
  23570. return this._singleClick;
  23571. },
  23572. set: function (b) {
  23573. this._singleClick = b;
  23574. },
  23575. enumerable: true,
  23576. configurable: true
  23577. });
  23578. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23579. get: function () {
  23580. return this._doubleClick;
  23581. },
  23582. set: function (b) {
  23583. this._doubleClick = b;
  23584. },
  23585. enumerable: true,
  23586. configurable: true
  23587. });
  23588. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23589. get: function () {
  23590. return this._hasSwiped;
  23591. },
  23592. set: function (b) {
  23593. this._hasSwiped = b;
  23594. },
  23595. enumerable: true,
  23596. configurable: true
  23597. });
  23598. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23599. get: function () {
  23600. return this._ignore;
  23601. },
  23602. set: function (b) {
  23603. this._ignore = b;
  23604. },
  23605. enumerable: true,
  23606. configurable: true
  23607. });
  23608. return ClickInfo;
  23609. }());
  23610. /**
  23611. * This class is used by the onRenderingGroupObservable
  23612. */
  23613. var RenderingGroupInfo = /** @class */ (function () {
  23614. function RenderingGroupInfo() {
  23615. }
  23616. /**
  23617. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23618. * This stage will be fired no matter what
  23619. */
  23620. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23621. /**
  23622. * Called before opaque object are rendered.
  23623. * This stage will be fired only if there's 3D Opaque content to render
  23624. */
  23625. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23626. /**
  23627. * Called after the opaque objects are rendered and before the transparent ones
  23628. * This stage will be fired only if there's 3D transparent content to render
  23629. */
  23630. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23631. /**
  23632. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23633. * This stage will be fired no matter what
  23634. */
  23635. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23636. return RenderingGroupInfo;
  23637. }());
  23638. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23639. /**
  23640. * Represents a scene to be rendered by the engine.
  23641. * @see http://doc.babylonjs.com/features/scene
  23642. */
  23643. var Scene = /** @class */ (function () {
  23644. /**
  23645. * Creates a new Scene
  23646. * @param engine defines the engine to use to render this scene
  23647. */
  23648. function Scene(engine) {
  23649. // Members
  23650. /**
  23651. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23652. */
  23653. this.autoClear = true;
  23654. /**
  23655. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23656. */
  23657. this.autoClearDepthAndStencil = true;
  23658. /**
  23659. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23660. */
  23661. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23662. /**
  23663. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23664. */
  23665. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23666. this._forceWireframe = false;
  23667. this._forcePointsCloud = false;
  23668. /**
  23669. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23670. */
  23671. this.forceShowBoundingBoxes = false;
  23672. /**
  23673. * Gets or sets a boolean indicating if animations are enabled
  23674. */
  23675. this.animationsEnabled = true;
  23676. this._animationPropertiesOverride = null;
  23677. /**
  23678. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23679. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23680. */
  23681. this.useConstantAnimationDeltaTime = false;
  23682. /**
  23683. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23684. * Please note that it requires to run a ray cast through the scene on every frame
  23685. */
  23686. this.constantlyUpdateMeshUnderPointer = false;
  23687. /**
  23688. * Defines the HTML cursor to use when hovering over interactive elements
  23689. */
  23690. this.hoverCursor = "pointer";
  23691. /**
  23692. * Defines the HTML default cursor to use (empty by default)
  23693. */
  23694. this.defaultCursor = "";
  23695. /**
  23696. * This is used to call preventDefault() on pointer down
  23697. * in order to block unwanted artifacts like system double clicks
  23698. */
  23699. this.preventDefaultOnPointerDown = true;
  23700. // Metadata
  23701. /**
  23702. * Gets or sets user defined metadata
  23703. */
  23704. this.metadata = null;
  23705. /**
  23706. * Use this array to add regular expressions used to disable offline support for specific urls
  23707. */
  23708. this.disableOfflineSupportExceptionRules = new Array();
  23709. /**
  23710. * An event triggered when the scene is disposed.
  23711. */
  23712. this.onDisposeObservable = new BABYLON.Observable();
  23713. this._onDisposeObserver = null;
  23714. /**
  23715. * An event triggered before rendering the scene (right after animations and physics)
  23716. */
  23717. this.onBeforeRenderObservable = new BABYLON.Observable();
  23718. this._onBeforeRenderObserver = null;
  23719. /**
  23720. * An event triggered after rendering the scene
  23721. */
  23722. this.onAfterRenderObservable = new BABYLON.Observable();
  23723. this._onAfterRenderObserver = null;
  23724. /**
  23725. * An event triggered before animating the scene
  23726. */
  23727. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23728. /**
  23729. * An event triggered after animations processing
  23730. */
  23731. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23732. /**
  23733. * An event triggered before draw calls are ready to be sent
  23734. */
  23735. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23736. /**
  23737. * An event triggered after draw calls have been sent
  23738. */
  23739. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23740. /**
  23741. * An event triggered when physic simulation is about to be run
  23742. */
  23743. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23744. /**
  23745. * An event triggered when physic simulation has been done
  23746. */
  23747. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23748. /**
  23749. * An event triggered when the scene is ready
  23750. */
  23751. this.onReadyObservable = new BABYLON.Observable();
  23752. /**
  23753. * An event triggered before rendering a camera
  23754. */
  23755. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23756. this._onBeforeCameraRenderObserver = null;
  23757. /**
  23758. * An event triggered after rendering a camera
  23759. */
  23760. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23761. this._onAfterCameraRenderObserver = null;
  23762. /**
  23763. * An event triggered when active meshes evaluation is about to start
  23764. */
  23765. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23766. /**
  23767. * An event triggered when active meshes evaluation is done
  23768. */
  23769. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23770. /**
  23771. * An event triggered when particles rendering is about to start
  23772. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23773. */
  23774. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23775. /**
  23776. * An event triggered when particles rendering is done
  23777. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23778. */
  23779. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23780. /**
  23781. * An event triggered when sprites rendering is about to start
  23782. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23783. */
  23784. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23785. /**
  23786. * An event triggered when sprites rendering is done
  23787. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23788. */
  23789. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23790. /**
  23791. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23792. */
  23793. this.onDataLoadedObservable = new BABYLON.Observable();
  23794. /**
  23795. * An event triggered when a camera is created
  23796. */
  23797. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23798. /**
  23799. * An event triggered when a camera is removed
  23800. */
  23801. this.onCameraRemovedObservable = new BABYLON.Observable();
  23802. /**
  23803. * An event triggered when a light is created
  23804. */
  23805. this.onNewLightAddedObservable = new BABYLON.Observable();
  23806. /**
  23807. * An event triggered when a light is removed
  23808. */
  23809. this.onLightRemovedObservable = new BABYLON.Observable();
  23810. /**
  23811. * An event triggered when a geometry is created
  23812. */
  23813. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23814. /**
  23815. * An event triggered when a geometry is removed
  23816. */
  23817. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23818. /**
  23819. * An event triggered when a transform node is created
  23820. */
  23821. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23822. /**
  23823. * An event triggered when a transform node is removed
  23824. */
  23825. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23826. /**
  23827. * An event triggered when a mesh is created
  23828. */
  23829. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23830. /**
  23831. * An event triggered when a mesh is removed
  23832. */
  23833. this.onMeshRemovedObservable = new BABYLON.Observable();
  23834. /**
  23835. * An event triggered when render targets are about to be rendered
  23836. * Can happen multiple times per frame.
  23837. */
  23838. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23839. /**
  23840. * An event triggered when render targets were rendered.
  23841. * Can happen multiple times per frame.
  23842. */
  23843. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23844. /**
  23845. * An event triggered before calculating deterministic simulation step
  23846. */
  23847. this.onBeforeStepObservable = new BABYLON.Observable();
  23848. /**
  23849. * An event triggered after calculating deterministic simulation step
  23850. */
  23851. this.onAfterStepObservable = new BABYLON.Observable();
  23852. /**
  23853. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23854. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23855. * 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)
  23856. */
  23857. this.onRenderingGroupObservable = new BABYLON.Observable();
  23858. // Animations
  23859. /**
  23860. * Gets a list of Animations associated with the scene
  23861. */
  23862. this.animations = [];
  23863. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23864. /**
  23865. * 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).
  23866. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23867. */
  23868. this.onPrePointerObservable = new BABYLON.Observable();
  23869. /**
  23870. * Observable event triggered each time an input event is received from the rendering canvas
  23871. */
  23872. this.onPointerObservable = new BABYLON.Observable();
  23873. this._meshPickProceed = false;
  23874. this._currentPickResult = null;
  23875. this._previousPickResult = null;
  23876. this._totalPointersPressed = 0;
  23877. this._doubleClickOccured = false;
  23878. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23879. this.cameraToUseForPointers = null;
  23880. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23881. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23882. this._startingPointerTime = 0;
  23883. this._previousStartingPointerTime = 0;
  23884. this._pointerCaptures = {};
  23885. // Deterministic lockstep
  23886. this._timeAccumulator = 0;
  23887. this._currentStepId = 0;
  23888. this._currentInternalStep = 0;
  23889. // Keyboard
  23890. /**
  23891. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23892. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23893. */
  23894. this.onPreKeyboardObservable = new BABYLON.Observable();
  23895. /**
  23896. * Observable event triggered each time an keyboard event is received from the hosting window
  23897. */
  23898. this.onKeyboardObservable = new BABYLON.Observable();
  23899. // Coordinates system
  23900. this._useRightHandedSystem = false;
  23901. // Fog
  23902. this._fogEnabled = true;
  23903. this._fogMode = Scene.FOGMODE_NONE;
  23904. /**
  23905. * Gets or sets the fog color to use
  23906. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23907. */
  23908. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23909. /**
  23910. * Gets or sets the fog density to use
  23911. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23912. */
  23913. this.fogDensity = 0.1;
  23914. /**
  23915. * Gets or sets the fog start distance to use
  23916. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23917. */
  23918. this.fogStart = 0;
  23919. /**
  23920. * Gets or sets the fog end distance to use
  23921. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23922. */
  23923. this.fogEnd = 1000.0;
  23924. // Lights
  23925. this._shadowsEnabled = true;
  23926. this._lightsEnabled = true;
  23927. /**
  23928. * All of the lights added to this scene
  23929. * @see http://doc.babylonjs.com/babylon101/lights
  23930. */
  23931. this.lights = new Array();
  23932. // Cameras
  23933. /** All of the cameras added to this scene.
  23934. * @see http://doc.babylonjs.com/babylon101/cameras
  23935. */
  23936. this.cameras = new Array();
  23937. /** All of the active cameras added to this scene. */
  23938. this.activeCameras = new Array();
  23939. // Meshes
  23940. /**
  23941. * All of the tranform nodes added to this scene
  23942. * @see http://doc.babylonjs.com/how_to/transformnode
  23943. */
  23944. this.transformNodes = new Array();
  23945. /**
  23946. * All of the (abstract) meshes added to this scene
  23947. */
  23948. this.meshes = new Array();
  23949. /**
  23950. * All of the animation groups added to this scene
  23951. * @see http://doc.babylonjs.com/how_to/group
  23952. */
  23953. this.animationGroups = new Array();
  23954. // Geometries
  23955. this._geometries = new Array();
  23956. /**
  23957. * All of the materials added to this scene
  23958. * @see http://doc.babylonjs.com/babylon101/materials
  23959. */
  23960. this.materials = new Array();
  23961. /**
  23962. * All of the multi-materials added to this scene
  23963. * @see http://doc.babylonjs.com/how_to/multi_materials
  23964. */
  23965. this.multiMaterials = new Array();
  23966. // Textures
  23967. this._texturesEnabled = true;
  23968. /**
  23969. * All of the textures added to this scene
  23970. */
  23971. this.textures = new Array();
  23972. // Particles
  23973. /**
  23974. * Gets or sets a boolean indicating if particles are enabled on this scene
  23975. */
  23976. this.particlesEnabled = true;
  23977. /**
  23978. * All of the particle systems added to this scene
  23979. * @see http://doc.babylonjs.com/babylon101/particles
  23980. */
  23981. this.particleSystems = new Array();
  23982. // Sprites
  23983. /**
  23984. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23985. */
  23986. this.spritesEnabled = true;
  23987. /**
  23988. * All of the sprite managers added to this scene
  23989. * @see http://doc.babylonjs.com/babylon101/sprites
  23990. */
  23991. this.spriteManagers = new Array();
  23992. /**
  23993. * The list of layers (background and foreground) of the scene
  23994. */
  23995. this.layers = new Array();
  23996. /**
  23997. * The list of effect layers (highlights/glow) added to the scene
  23998. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23999. * @see http://doc.babylonjs.com/how_to/glow_layer
  24000. */
  24001. this.effectLayers = new Array();
  24002. // Skeletons
  24003. this._skeletonsEnabled = true;
  24004. /**
  24005. * The list of skeletons added to the scene
  24006. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24007. */
  24008. this.skeletons = new Array();
  24009. // Morph targets
  24010. /**
  24011. * The list of morph target managers added to the scene
  24012. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24013. */
  24014. this.morphTargetManagers = new Array();
  24015. // Lens flares
  24016. /**
  24017. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24018. */
  24019. this.lensFlaresEnabled = true;
  24020. /**
  24021. * The list of lens flare system added to the scene
  24022. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24023. */
  24024. this.lensFlareSystems = new Array();
  24025. // Collisions
  24026. /**
  24027. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24028. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24029. */
  24030. this.collisionsEnabled = true;
  24031. /**
  24032. * Defines the gravity applied to this scene (used only for collisions)
  24033. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24034. */
  24035. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24036. // Postprocesses
  24037. /**
  24038. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24039. */
  24040. this.postProcessesEnabled = true;
  24041. /**
  24042. * The list of postprocesses added to the scene
  24043. */
  24044. this.postProcesses = new Array();
  24045. // Customs render targets
  24046. /**
  24047. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24048. */
  24049. this.renderTargetsEnabled = true;
  24050. /**
  24051. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24052. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24053. */
  24054. this.dumpNextRenderTargets = false;
  24055. /**
  24056. * The list of user defined render targets added to the scene
  24057. */
  24058. this.customRenderTargets = new Array();
  24059. /**
  24060. * Gets the list of meshes imported to the scene through SceneLoader
  24061. */
  24062. this.importedMeshesFiles = new Array();
  24063. // Probes
  24064. /**
  24065. * Gets or sets a boolean indicating if probes are enabled on this scene
  24066. */
  24067. this.probesEnabled = true;
  24068. /**
  24069. * The list of reflection probes added to the scene
  24070. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24071. */
  24072. this.reflectionProbes = new Array();
  24073. /** @hidden */
  24074. this._actionManagers = new Array();
  24075. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24076. // Procedural textures
  24077. /**
  24078. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24079. */
  24080. this.proceduralTexturesEnabled = true;
  24081. /**
  24082. * The list of procedural textures added to the scene
  24083. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24084. */
  24085. this.proceduralTextures = new Array();
  24086. /**
  24087. * The list of sound tracks added to the scene
  24088. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24089. */
  24090. this.soundTracks = new Array();
  24091. this._audioEnabled = true;
  24092. this._headphone = false;
  24093. // Performance counters
  24094. this._totalVertices = new BABYLON.PerfCounter();
  24095. /** @hidden */
  24096. this._activeIndices = new BABYLON.PerfCounter();
  24097. /** @hidden */
  24098. this._activeParticles = new BABYLON.PerfCounter();
  24099. /** @hidden */
  24100. this._activeBones = new BABYLON.PerfCounter();
  24101. this._animationTime = 0;
  24102. /**
  24103. * Gets or sets a general scale for animation speed
  24104. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24105. */
  24106. this.animationTimeScale = 1;
  24107. this._renderId = 0;
  24108. this._executeWhenReadyTimeoutId = -1;
  24109. this._intermediateRendering = false;
  24110. this._viewUpdateFlag = -1;
  24111. this._projectionUpdateFlag = -1;
  24112. this._alternateViewUpdateFlag = -1;
  24113. this._alternateProjectionUpdateFlag = -1;
  24114. /** @hidden */
  24115. this._toBeDisposed = new BABYLON.SmartArray(256);
  24116. this._activeRequests = new Array();
  24117. this._pendingData = new Array();
  24118. this._isDisposed = false;
  24119. /**
  24120. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24121. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24122. */
  24123. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24124. this._activeMeshes = new BABYLON.SmartArray(256);
  24125. this._processedMaterials = new BABYLON.SmartArray(256);
  24126. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24127. /** @hidden */
  24128. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24129. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24130. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24131. /** @hidden */
  24132. this._activeAnimatables = new Array();
  24133. this._transformMatrix = BABYLON.Matrix.Zero();
  24134. this._useAlternateCameraConfiguration = false;
  24135. this._alternateRendering = false;
  24136. /**
  24137. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24138. * This is useful if there are more lights that the maximum simulteanous authorized
  24139. */
  24140. this.requireLightSorting = false;
  24141. this._depthRenderer = {};
  24142. this._activeMeshesFrozen = false;
  24143. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24144. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24145. this._engine.scenes.push(this);
  24146. this._uid = null;
  24147. this._renderingManager = new BABYLON.RenderingManager(this);
  24148. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24149. if (BABYLON.OutlineRenderer) {
  24150. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24151. }
  24152. if (BABYLON.Tools.IsWindowObjectExist()) {
  24153. this.attachControl();
  24154. }
  24155. //simplification queue
  24156. if (BABYLON.SimplificationQueue) {
  24157. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24158. }
  24159. //collision coordinator initialization. For now legacy per default.
  24160. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24161. // Uniform Buffer
  24162. this._createUbo();
  24163. // Default Image processing definition.
  24164. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24165. }
  24166. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24167. /** The fog is deactivated */
  24168. get: function () {
  24169. return Scene._FOGMODE_NONE;
  24170. },
  24171. enumerable: true,
  24172. configurable: true
  24173. });
  24174. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24175. /** The fog density is following an exponential function */
  24176. get: function () {
  24177. return Scene._FOGMODE_EXP;
  24178. },
  24179. enumerable: true,
  24180. configurable: true
  24181. });
  24182. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24183. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24184. get: function () {
  24185. return Scene._FOGMODE_EXP2;
  24186. },
  24187. enumerable: true,
  24188. configurable: true
  24189. });
  24190. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24191. /** The fog density is following a linear function. */
  24192. get: function () {
  24193. return Scene._FOGMODE_LINEAR;
  24194. },
  24195. enumerable: true,
  24196. configurable: true
  24197. });
  24198. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24199. /**
  24200. * Texture used in all pbr material as the reflection texture.
  24201. * As in the majority of the scene they are the same (exception for multi room and so on),
  24202. * this is easier to reference from here than from all the materials.
  24203. */
  24204. get: function () {
  24205. return this._environmentTexture;
  24206. },
  24207. /**
  24208. * Texture used in all pbr material as the reflection texture.
  24209. * As in the majority of the scene they are the same (exception for multi room and so on),
  24210. * this is easier to set here than in all the materials.
  24211. */
  24212. set: function (value) {
  24213. if (this._environmentTexture === value) {
  24214. return;
  24215. }
  24216. this._environmentTexture = value;
  24217. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24218. },
  24219. enumerable: true,
  24220. configurable: true
  24221. });
  24222. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24223. /**
  24224. * Default image processing configuration used either in the rendering
  24225. * Forward main pass or through the imageProcessingPostProcess if present.
  24226. * As in the majority of the scene they are the same (exception for multi camera),
  24227. * this is easier to reference from here than from all the materials and post process.
  24228. *
  24229. * No setter as we it is a shared configuration, you can set the values instead.
  24230. */
  24231. get: function () {
  24232. return this._imageProcessingConfiguration;
  24233. },
  24234. enumerable: true,
  24235. configurable: true
  24236. });
  24237. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24238. get: function () {
  24239. return this._forceWireframe;
  24240. },
  24241. /**
  24242. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24243. */
  24244. set: function (value) {
  24245. if (this._forceWireframe === value) {
  24246. return;
  24247. }
  24248. this._forceWireframe = value;
  24249. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24250. },
  24251. enumerable: true,
  24252. configurable: true
  24253. });
  24254. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24255. get: function () {
  24256. return this._forcePointsCloud;
  24257. },
  24258. /**
  24259. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24260. */
  24261. set: function (value) {
  24262. if (this._forcePointsCloud === value) {
  24263. return;
  24264. }
  24265. this._forcePointsCloud = value;
  24266. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24267. },
  24268. enumerable: true,
  24269. configurable: true
  24270. });
  24271. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24272. /**
  24273. * Gets or sets the animation properties override
  24274. */
  24275. get: function () {
  24276. return this._animationPropertiesOverride;
  24277. },
  24278. set: function (value) {
  24279. this._animationPropertiesOverride = value;
  24280. },
  24281. enumerable: true,
  24282. configurable: true
  24283. });
  24284. Object.defineProperty(Scene.prototype, "onDispose", {
  24285. /** Sets a function to be executed when this scene is disposed. */
  24286. set: function (callback) {
  24287. if (this._onDisposeObserver) {
  24288. this.onDisposeObservable.remove(this._onDisposeObserver);
  24289. }
  24290. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24291. },
  24292. enumerable: true,
  24293. configurable: true
  24294. });
  24295. Object.defineProperty(Scene.prototype, "beforeRender", {
  24296. /** Sets a function to be executed before rendering this scene */
  24297. set: function (callback) {
  24298. if (this._onBeforeRenderObserver) {
  24299. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24300. }
  24301. if (callback) {
  24302. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24303. }
  24304. },
  24305. enumerable: true,
  24306. configurable: true
  24307. });
  24308. Object.defineProperty(Scene.prototype, "afterRender", {
  24309. /** Sets a function to be executed after rendering this scene */
  24310. set: function (callback) {
  24311. if (this._onAfterRenderObserver) {
  24312. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24313. }
  24314. if (callback) {
  24315. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24316. }
  24317. },
  24318. enumerable: true,
  24319. configurable: true
  24320. });
  24321. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24322. /** Sets a function to be executed before rendering a camera*/
  24323. set: function (callback) {
  24324. if (this._onBeforeCameraRenderObserver) {
  24325. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24326. }
  24327. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24328. },
  24329. enumerable: true,
  24330. configurable: true
  24331. });
  24332. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24333. /** Sets a function to be executed after rendering a camera*/
  24334. set: function (callback) {
  24335. if (this._onAfterCameraRenderObserver) {
  24336. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24337. }
  24338. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24339. },
  24340. enumerable: true,
  24341. configurable: true
  24342. });
  24343. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24344. /**
  24345. * Gets the gamepad manager associated with the scene
  24346. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24347. */
  24348. get: function () {
  24349. if (!this._gamepadManager) {
  24350. this._gamepadManager = new BABYLON.GamepadManager(this);
  24351. }
  24352. return this._gamepadManager;
  24353. },
  24354. enumerable: true,
  24355. configurable: true
  24356. });
  24357. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24358. /**
  24359. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24360. */
  24361. get: function () {
  24362. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24363. },
  24364. enumerable: true,
  24365. configurable: true
  24366. });
  24367. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24368. get: function () {
  24369. return this._useRightHandedSystem;
  24370. },
  24371. /**
  24372. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24373. */
  24374. set: function (value) {
  24375. if (this._useRightHandedSystem === value) {
  24376. return;
  24377. }
  24378. this._useRightHandedSystem = value;
  24379. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24380. },
  24381. enumerable: true,
  24382. configurable: true
  24383. });
  24384. /**
  24385. * Sets the step Id used by deterministic lock step
  24386. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24387. * @param newStepId defines the step Id
  24388. */
  24389. Scene.prototype.setStepId = function (newStepId) {
  24390. this._currentStepId = newStepId;
  24391. };
  24392. ;
  24393. /**
  24394. * Gets the step Id used by deterministic lock step
  24395. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24396. * @returns the step Id
  24397. */
  24398. Scene.prototype.getStepId = function () {
  24399. return this._currentStepId;
  24400. };
  24401. ;
  24402. /**
  24403. * Gets the internal step used by deterministic lock step
  24404. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24405. * @returns the internal step
  24406. */
  24407. Scene.prototype.getInternalStep = function () {
  24408. return this._currentInternalStep;
  24409. };
  24410. ;
  24411. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24412. get: function () {
  24413. return this._fogEnabled;
  24414. },
  24415. /**
  24416. * Gets or sets a boolean indicating if fog is enabled on this scene
  24417. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24418. */
  24419. set: function (value) {
  24420. if (this._fogEnabled === value) {
  24421. return;
  24422. }
  24423. this._fogEnabled = value;
  24424. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24425. },
  24426. enumerable: true,
  24427. configurable: true
  24428. });
  24429. Object.defineProperty(Scene.prototype, "fogMode", {
  24430. get: function () {
  24431. return this._fogMode;
  24432. },
  24433. /**
  24434. * Gets or sets the fog mode to use
  24435. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24436. */
  24437. set: function (value) {
  24438. if (this._fogMode === value) {
  24439. return;
  24440. }
  24441. this._fogMode = value;
  24442. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24443. },
  24444. enumerable: true,
  24445. configurable: true
  24446. });
  24447. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24448. get: function () {
  24449. return this._shadowsEnabled;
  24450. },
  24451. /**
  24452. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24453. */
  24454. set: function (value) {
  24455. if (this._shadowsEnabled === value) {
  24456. return;
  24457. }
  24458. this._shadowsEnabled = value;
  24459. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24460. },
  24461. enumerable: true,
  24462. configurable: true
  24463. });
  24464. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24465. get: function () {
  24466. return this._lightsEnabled;
  24467. },
  24468. /**
  24469. * Gets or sets a boolean indicating if lights are enabled on this scene
  24470. */
  24471. set: function (value) {
  24472. if (this._lightsEnabled === value) {
  24473. return;
  24474. }
  24475. this._lightsEnabled = value;
  24476. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24477. },
  24478. enumerable: true,
  24479. configurable: true
  24480. });
  24481. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24482. /** The default material used on meshes when no material is affected */
  24483. get: function () {
  24484. if (!this._defaultMaterial) {
  24485. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24486. }
  24487. return this._defaultMaterial;
  24488. },
  24489. /** The default material used on meshes when no material is affected */
  24490. set: function (value) {
  24491. this._defaultMaterial = value;
  24492. },
  24493. enumerable: true,
  24494. configurable: true
  24495. });
  24496. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24497. get: function () {
  24498. return this._texturesEnabled;
  24499. },
  24500. /**
  24501. * Gets or sets a boolean indicating if textures are enabled on this scene
  24502. */
  24503. set: function (value) {
  24504. if (this._texturesEnabled === value) {
  24505. return;
  24506. }
  24507. this._texturesEnabled = value;
  24508. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24509. },
  24510. enumerable: true,
  24511. configurable: true
  24512. });
  24513. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24514. get: function () {
  24515. return this._skeletonsEnabled;
  24516. },
  24517. /**
  24518. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24519. */
  24520. set: function (value) {
  24521. if (this._skeletonsEnabled === value) {
  24522. return;
  24523. }
  24524. this._skeletonsEnabled = value;
  24525. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24526. },
  24527. enumerable: true,
  24528. configurable: true
  24529. });
  24530. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24531. /**
  24532. * Gets the postprocess render pipeline manager
  24533. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24534. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24535. */
  24536. get: function () {
  24537. if (!this._postProcessRenderPipelineManager) {
  24538. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24539. }
  24540. return this._postProcessRenderPipelineManager;
  24541. },
  24542. enumerable: true,
  24543. configurable: true
  24544. });
  24545. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24546. /**
  24547. * Gets the main soundtrack associated with the scene
  24548. */
  24549. get: function () {
  24550. if (!this._mainSoundTrack) {
  24551. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24552. }
  24553. return this._mainSoundTrack;
  24554. },
  24555. enumerable: true,
  24556. configurable: true
  24557. });
  24558. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24559. /** @hidden */
  24560. get: function () {
  24561. return this._alternateRendering;
  24562. },
  24563. enumerable: true,
  24564. configurable: true
  24565. });
  24566. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24567. /**
  24568. * Gets the list of frustum planes (built from the active camera)
  24569. */
  24570. get: function () {
  24571. return this._frustumPlanes;
  24572. },
  24573. enumerable: true,
  24574. configurable: true
  24575. });
  24576. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24577. /**
  24578. * Gets the current geometry buffer associated to the scene.
  24579. */
  24580. get: function () {
  24581. return this._geometryBufferRenderer;
  24582. },
  24583. /**
  24584. * Sets the current geometry buffer for the scene.
  24585. */
  24586. set: function (geometryBufferRenderer) {
  24587. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24588. this._geometryBufferRenderer = geometryBufferRenderer;
  24589. }
  24590. },
  24591. enumerable: true,
  24592. configurable: true
  24593. });
  24594. Object.defineProperty(Scene.prototype, "debugLayer", {
  24595. /**
  24596. * Gets the debug layer associated with the scene
  24597. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24598. */
  24599. get: function () {
  24600. if (!this._debugLayer) {
  24601. this._debugLayer = new BABYLON.DebugLayer(this);
  24602. }
  24603. return this._debugLayer;
  24604. },
  24605. enumerable: true,
  24606. configurable: true
  24607. });
  24608. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24609. /**
  24610. * Gets a boolean indicating if collisions are processed on a web worker
  24611. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24612. */
  24613. get: function () {
  24614. return this._workerCollisions;
  24615. },
  24616. set: function (enabled) {
  24617. if (!BABYLON.CollisionCoordinatorLegacy) {
  24618. return;
  24619. }
  24620. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24621. this._workerCollisions = enabled;
  24622. if (this.collisionCoordinator) {
  24623. this.collisionCoordinator.destroy();
  24624. }
  24625. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24626. this.collisionCoordinator.init(this);
  24627. },
  24628. enumerable: true,
  24629. configurable: true
  24630. });
  24631. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24632. /**
  24633. * Gets the octree used to boost mesh selection (picking)
  24634. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24635. */
  24636. get: function () {
  24637. return this._selectionOctree;
  24638. },
  24639. enumerable: true,
  24640. configurable: true
  24641. });
  24642. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24643. /**
  24644. * Gets the mesh that is currently under the pointer
  24645. */
  24646. get: function () {
  24647. return this._pointerOverMesh;
  24648. },
  24649. enumerable: true,
  24650. configurable: true
  24651. });
  24652. Object.defineProperty(Scene.prototype, "pointerX", {
  24653. /**
  24654. * Gets the current on-screen X position of the pointer
  24655. */
  24656. get: function () {
  24657. return this._pointerX;
  24658. },
  24659. enumerable: true,
  24660. configurable: true
  24661. });
  24662. Object.defineProperty(Scene.prototype, "pointerY", {
  24663. /**
  24664. * Gets the current on-screen Y position of the pointer
  24665. */
  24666. get: function () {
  24667. return this._pointerY;
  24668. },
  24669. enumerable: true,
  24670. configurable: true
  24671. });
  24672. /**
  24673. * Gets the cached material (ie. the latest rendered one)
  24674. * @returns the cached material
  24675. */
  24676. Scene.prototype.getCachedMaterial = function () {
  24677. return this._cachedMaterial;
  24678. };
  24679. /**
  24680. * Gets the cached effect (ie. the latest rendered one)
  24681. * @returns the cached effect
  24682. */
  24683. Scene.prototype.getCachedEffect = function () {
  24684. return this._cachedEffect;
  24685. };
  24686. /**
  24687. * Gets the cached visibility state (ie. the latest rendered one)
  24688. * @returns the cached visibility state
  24689. */
  24690. Scene.prototype.getCachedVisibility = function () {
  24691. return this._cachedVisibility;
  24692. };
  24693. /**
  24694. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24695. * @param material defines the current material
  24696. * @param effect defines the current effect
  24697. * @param visibility defines the current visibility state
  24698. * @returns true if one parameter is not cached
  24699. */
  24700. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24701. if (visibility === void 0) { visibility = 1; }
  24702. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24703. };
  24704. /**
  24705. * Gets the bounding box renderer associated with the scene
  24706. * @returns a BoundingBoxRenderer
  24707. */
  24708. Scene.prototype.getBoundingBoxRenderer = function () {
  24709. if (!this._boundingBoxRenderer) {
  24710. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24711. }
  24712. return this._boundingBoxRenderer;
  24713. };
  24714. /**
  24715. * Gets the outline renderer associated with the scene
  24716. * @returns a OutlineRenderer
  24717. */
  24718. Scene.prototype.getOutlineRenderer = function () {
  24719. return this._outlineRenderer;
  24720. };
  24721. /**
  24722. * Gets the engine associated with the scene
  24723. * @returns an Engine
  24724. */
  24725. Scene.prototype.getEngine = function () {
  24726. return this._engine;
  24727. };
  24728. /**
  24729. * Gets the total number of vertices rendered per frame
  24730. * @returns the total number of vertices rendered per frame
  24731. */
  24732. Scene.prototype.getTotalVertices = function () {
  24733. return this._totalVertices.current;
  24734. };
  24735. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24736. /**
  24737. * Gets the performance counter for total vertices
  24738. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24739. */
  24740. get: function () {
  24741. return this._totalVertices;
  24742. },
  24743. enumerable: true,
  24744. configurable: true
  24745. });
  24746. /**
  24747. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24748. * @returns the total number of active indices rendered per frame
  24749. */
  24750. Scene.prototype.getActiveIndices = function () {
  24751. return this._activeIndices.current;
  24752. };
  24753. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24754. /**
  24755. * Gets the performance counter for active indices
  24756. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24757. */
  24758. get: function () {
  24759. return this._activeIndices;
  24760. },
  24761. enumerable: true,
  24762. configurable: true
  24763. });
  24764. /**
  24765. * Gets the total number of active particles rendered per frame
  24766. * @returns the total number of active particles rendered per frame
  24767. */
  24768. Scene.prototype.getActiveParticles = function () {
  24769. return this._activeParticles.current;
  24770. };
  24771. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24772. /**
  24773. * Gets the performance counter for active particles
  24774. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24775. */
  24776. get: function () {
  24777. return this._activeParticles;
  24778. },
  24779. enumerable: true,
  24780. configurable: true
  24781. });
  24782. /**
  24783. * Gets the total number of active bones rendered per frame
  24784. * @returns the total number of active bones rendered per frame
  24785. */
  24786. Scene.prototype.getActiveBones = function () {
  24787. return this._activeBones.current;
  24788. };
  24789. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24790. /**
  24791. * Gets the performance counter for active bones
  24792. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24793. */
  24794. get: function () {
  24795. return this._activeBones;
  24796. },
  24797. enumerable: true,
  24798. configurable: true
  24799. });
  24800. /** @hidden */
  24801. Scene.prototype.getInterFramePerfCounter = function () {
  24802. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24803. return 0;
  24804. };
  24805. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24806. /** @hidden */
  24807. get: function () {
  24808. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24809. return null;
  24810. },
  24811. enumerable: true,
  24812. configurable: true
  24813. });
  24814. /** @hidden */
  24815. Scene.prototype.getLastFrameDuration = function () {
  24816. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24817. return 0;
  24818. };
  24819. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24820. /** @hidden */
  24821. get: function () {
  24822. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24823. return null;
  24824. },
  24825. enumerable: true,
  24826. configurable: true
  24827. });
  24828. /** @hidden */
  24829. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24830. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24831. return 0;
  24832. };
  24833. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24834. /** @hidden */
  24835. get: function () {
  24836. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24837. return null;
  24838. },
  24839. enumerable: true,
  24840. configurable: true
  24841. });
  24842. /**
  24843. * Gets the array of active meshes
  24844. * @returns an array of AbstractMesh
  24845. */
  24846. Scene.prototype.getActiveMeshes = function () {
  24847. return this._activeMeshes;
  24848. };
  24849. /** @hidden */
  24850. Scene.prototype.getRenderTargetsDuration = function () {
  24851. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24852. return 0;
  24853. };
  24854. /** @hidden */
  24855. Scene.prototype.getRenderDuration = function () {
  24856. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24857. return 0;
  24858. };
  24859. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24860. /** @hidden */
  24861. get: function () {
  24862. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24863. return null;
  24864. },
  24865. enumerable: true,
  24866. configurable: true
  24867. });
  24868. /** @hidden */
  24869. Scene.prototype.getParticlesDuration = function () {
  24870. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24871. return 0;
  24872. };
  24873. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24874. /** @hidden */
  24875. get: function () {
  24876. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24877. return null;
  24878. },
  24879. enumerable: true,
  24880. configurable: true
  24881. });
  24882. /** @hidden */
  24883. Scene.prototype.getSpritesDuration = function () {
  24884. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24885. return 0;
  24886. };
  24887. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24888. /** @hidden */
  24889. get: function () {
  24890. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24891. return null;
  24892. },
  24893. enumerable: true,
  24894. configurable: true
  24895. });
  24896. /**
  24897. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24898. * @returns a number
  24899. */
  24900. Scene.prototype.getAnimationRatio = function () {
  24901. return this._animationRatio;
  24902. };
  24903. /**
  24904. * Gets an unique Id for the current frame
  24905. * @returns a number
  24906. */
  24907. Scene.prototype.getRenderId = function () {
  24908. return this._renderId;
  24909. };
  24910. /** Call this function if you want to manually increment the render Id*/
  24911. Scene.prototype.incrementRenderId = function () {
  24912. this._renderId++;
  24913. };
  24914. Scene.prototype._updatePointerPosition = function (evt) {
  24915. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24916. if (!canvasRect) {
  24917. return;
  24918. }
  24919. this._pointerX = evt.clientX - canvasRect.left;
  24920. this._pointerY = evt.clientY - canvasRect.top;
  24921. this._unTranslatedPointerX = this._pointerX;
  24922. this._unTranslatedPointerY = this._pointerY;
  24923. };
  24924. Scene.prototype._createUbo = function () {
  24925. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24926. this._sceneUbo.addUniform("viewProjection", 16);
  24927. this._sceneUbo.addUniform("view", 16);
  24928. };
  24929. Scene.prototype._createAlternateUbo = function () {
  24930. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24931. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24932. this._alternateSceneUbo.addUniform("view", 16);
  24933. };
  24934. // Pointers handling
  24935. /**
  24936. * Use this method to simulate a pointer move on a mesh
  24937. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24938. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24939. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24940. * @returns the current scene
  24941. */
  24942. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24943. var evt = new PointerEvent("pointermove", pointerEventInit);
  24944. return this._processPointerMove(pickResult, evt);
  24945. };
  24946. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24947. var canvas = this._engine.getRenderingCanvas();
  24948. if (!canvas) {
  24949. return this;
  24950. }
  24951. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24952. this.setPointerOverSprite(null);
  24953. this.setPointerOverMesh(pickResult.pickedMesh);
  24954. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24955. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24956. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24957. }
  24958. else {
  24959. canvas.style.cursor = this.hoverCursor;
  24960. }
  24961. }
  24962. else {
  24963. canvas.style.cursor = this.defaultCursor;
  24964. }
  24965. }
  24966. else {
  24967. this.setPointerOverMesh(null);
  24968. // Sprites
  24969. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24970. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24971. this.setPointerOverSprite(pickResult.pickedSprite);
  24972. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24973. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24974. }
  24975. else {
  24976. canvas.style.cursor = this.hoverCursor;
  24977. }
  24978. }
  24979. else {
  24980. this.setPointerOverSprite(null);
  24981. // Restore pointer
  24982. canvas.style.cursor = this.defaultCursor;
  24983. }
  24984. }
  24985. if (pickResult) {
  24986. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24987. if (this.onPointerMove) {
  24988. this.onPointerMove(evt, pickResult, type);
  24989. }
  24990. if (this.onPointerObservable.hasObservers()) {
  24991. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24992. this.onPointerObservable.notifyObservers(pi, type);
  24993. }
  24994. }
  24995. return this;
  24996. };
  24997. /**
  24998. * Use this method to simulate a pointer down on a mesh
  24999. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25000. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25001. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25002. * @returns the current scene
  25003. */
  25004. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25005. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25006. return this._processPointerDown(pickResult, evt);
  25007. };
  25008. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25009. var _this = this;
  25010. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25011. this._pickedDownMesh = pickResult.pickedMesh;
  25012. var actionManager = pickResult.pickedMesh.actionManager;
  25013. if (actionManager) {
  25014. if (actionManager.hasPickTriggers) {
  25015. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25016. switch (evt.button) {
  25017. case 0:
  25018. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25019. break;
  25020. case 1:
  25021. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25022. break;
  25023. case 2:
  25024. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25025. break;
  25026. }
  25027. }
  25028. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25029. window.setTimeout(function () {
  25030. 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);
  25031. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25032. if (_this._totalPointersPressed !== 0 &&
  25033. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25034. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25035. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25036. _this._startingPointerTime = 0;
  25037. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25038. }
  25039. }
  25040. }, Scene.LongPressDelay);
  25041. }
  25042. }
  25043. }
  25044. if (pickResult) {
  25045. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25046. if (this.onPointerDown) {
  25047. this.onPointerDown(evt, pickResult, type);
  25048. }
  25049. if (this.onPointerObservable.hasObservers()) {
  25050. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25051. this.onPointerObservable.notifyObservers(pi, type);
  25052. }
  25053. }
  25054. return this;
  25055. };
  25056. /**
  25057. * Use this method to simulate a pointer up on a mesh
  25058. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25059. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25060. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25061. * @returns the current scene
  25062. */
  25063. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25064. var evt = new PointerEvent("pointerup", pointerEventInit);
  25065. var clickInfo = new ClickInfo();
  25066. clickInfo.singleClick = true;
  25067. clickInfo.ignore = true;
  25068. return this._processPointerUp(pickResult, evt, clickInfo);
  25069. };
  25070. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25071. if (pickResult && pickResult && pickResult.pickedMesh) {
  25072. this._pickedUpMesh = pickResult.pickedMesh;
  25073. if (this._pickedDownMesh === this._pickedUpMesh) {
  25074. if (this.onPointerPick) {
  25075. this.onPointerPick(evt, pickResult);
  25076. }
  25077. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25078. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25079. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25080. this.onPointerObservable.notifyObservers(pi, type_1);
  25081. }
  25082. }
  25083. if (pickResult.pickedMesh.actionManager) {
  25084. if (clickInfo.ignore) {
  25085. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25086. }
  25087. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25088. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25089. }
  25090. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25091. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25092. }
  25093. }
  25094. }
  25095. if (this._pickedDownMesh &&
  25096. this._pickedDownMesh.actionManager &&
  25097. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25098. this._pickedDownMesh !== this._pickedUpMesh) {
  25099. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25100. }
  25101. var type = BABYLON.PointerEventTypes.POINTERUP;
  25102. if (this.onPointerObservable.hasObservers()) {
  25103. if (!clickInfo.ignore) {
  25104. if (!clickInfo.hasSwiped) {
  25105. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25106. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25107. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25108. this.onPointerObservable.notifyObservers(pi, type_2);
  25109. }
  25110. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25111. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25112. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25113. this.onPointerObservable.notifyObservers(pi, type_3);
  25114. }
  25115. }
  25116. }
  25117. else {
  25118. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25119. this.onPointerObservable.notifyObservers(pi, type);
  25120. }
  25121. }
  25122. if (this.onPointerUp) {
  25123. this.onPointerUp(evt, pickResult, type);
  25124. }
  25125. return this;
  25126. };
  25127. /**
  25128. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25129. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25130. * @returns true if the pointer was captured
  25131. */
  25132. Scene.prototype.isPointerCaptured = function (pointerId) {
  25133. if (pointerId === void 0) { pointerId = 0; }
  25134. return this._pointerCaptures[pointerId];
  25135. };
  25136. /**
  25137. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25138. * @param attachUp defines if you want to attach events to pointerup
  25139. * @param attachDown defines if you want to attach events to pointerdown
  25140. * @param attachMove defines if you want to attach events to pointermove
  25141. */
  25142. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25143. var _this = this;
  25144. if (attachUp === void 0) { attachUp = true; }
  25145. if (attachDown === void 0) { attachDown = true; }
  25146. if (attachMove === void 0) { attachMove = true; }
  25147. this._initActionManager = function (act, clickInfo) {
  25148. if (!_this._meshPickProceed) {
  25149. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25150. _this._currentPickResult = pickResult;
  25151. if (pickResult) {
  25152. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25153. }
  25154. _this._meshPickProceed = true;
  25155. }
  25156. return act;
  25157. };
  25158. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25159. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25160. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25161. btn !== _this._previousButtonPressed) {
  25162. _this._doubleClickOccured = false;
  25163. clickInfo.singleClick = true;
  25164. clickInfo.ignore = false;
  25165. cb(clickInfo, _this._currentPickResult);
  25166. }
  25167. };
  25168. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25169. var clickInfo = new ClickInfo();
  25170. _this._currentPickResult = null;
  25171. var act = null;
  25172. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25173. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25174. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25175. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25176. act = _this._initActionManager(act, clickInfo);
  25177. if (act)
  25178. checkPicking = act.hasPickTriggers;
  25179. }
  25180. if (checkPicking) {
  25181. var btn = evt.button;
  25182. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25183. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25184. if (!clickInfo.hasSwiped) {
  25185. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25186. if (!checkSingleClickImmediately) {
  25187. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25188. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25189. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25190. act = _this._initActionManager(act, clickInfo);
  25191. if (act)
  25192. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25193. }
  25194. }
  25195. if (checkSingleClickImmediately) {
  25196. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25197. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25198. btn !== _this._previousButtonPressed) {
  25199. clickInfo.singleClick = true;
  25200. cb(clickInfo, _this._currentPickResult);
  25201. }
  25202. }
  25203. // at least one double click is required to be check and exclusive double click is enabled
  25204. else {
  25205. // wait that no double click has been raised during the double click delay
  25206. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25207. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25208. }
  25209. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25210. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25211. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25212. act = _this._initActionManager(act, clickInfo);
  25213. if (act)
  25214. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25215. }
  25216. if (checkDoubleClick) {
  25217. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25218. if (btn === _this._previousButtonPressed &&
  25219. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25220. !_this._doubleClickOccured) {
  25221. // pointer has not moved for 2 clicks, it's a double click
  25222. if (!clickInfo.hasSwiped &&
  25223. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25224. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25225. _this._previousStartingPointerTime = 0;
  25226. _this._doubleClickOccured = true;
  25227. clickInfo.doubleClick = true;
  25228. clickInfo.ignore = false;
  25229. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25230. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25231. }
  25232. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25233. cb(clickInfo, _this._currentPickResult);
  25234. }
  25235. // if the two successive clicks are too far, it's just two simple clicks
  25236. else {
  25237. _this._doubleClickOccured = false;
  25238. _this._previousStartingPointerTime = _this._startingPointerTime;
  25239. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25240. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25241. _this._previousButtonPressed = btn;
  25242. if (Scene.ExclusiveDoubleClickMode) {
  25243. if (_this._previousDelayedSimpleClickTimeout) {
  25244. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25245. }
  25246. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25247. cb(clickInfo, _this._previousPickResult);
  25248. }
  25249. else {
  25250. cb(clickInfo, _this._currentPickResult);
  25251. }
  25252. }
  25253. }
  25254. // just the first click of the double has been raised
  25255. else {
  25256. _this._doubleClickOccured = false;
  25257. _this._previousStartingPointerTime = _this._startingPointerTime;
  25258. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25259. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25260. _this._previousButtonPressed = btn;
  25261. }
  25262. }
  25263. }
  25264. }
  25265. clickInfo.ignore = true;
  25266. cb(clickInfo, _this._currentPickResult);
  25267. };
  25268. this._spritePredicate = function (sprite) {
  25269. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25270. };
  25271. this._onPointerMove = function (evt) {
  25272. _this._updatePointerPosition(evt);
  25273. // PreObservable support
  25274. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25275. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25276. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25277. _this.onPrePointerObservable.notifyObservers(pi, type);
  25278. if (pi.skipOnPointerObservable) {
  25279. return;
  25280. }
  25281. }
  25282. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25283. return;
  25284. }
  25285. if (!_this.pointerMovePredicate) {
  25286. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25287. }
  25288. // Meshes
  25289. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25290. _this._processPointerMove(pickResult, evt);
  25291. };
  25292. this._onPointerDown = function (evt) {
  25293. _this._totalPointersPressed++;
  25294. _this._pickedDownMesh = null;
  25295. _this._meshPickProceed = false;
  25296. _this._updatePointerPosition(evt);
  25297. if (_this.preventDefaultOnPointerDown && canvas) {
  25298. evt.preventDefault();
  25299. canvas.focus();
  25300. }
  25301. // PreObservable support
  25302. if (_this.onPrePointerObservable.hasObservers()) {
  25303. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25304. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25305. _this.onPrePointerObservable.notifyObservers(pi, type);
  25306. if (pi.skipOnPointerObservable) {
  25307. return;
  25308. }
  25309. }
  25310. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25311. return;
  25312. }
  25313. _this._pointerCaptures[evt.pointerId] = true;
  25314. _this._startingPointerPosition.x = _this._pointerX;
  25315. _this._startingPointerPosition.y = _this._pointerY;
  25316. _this._startingPointerTime = Date.now();
  25317. if (!_this.pointerDownPredicate) {
  25318. _this.pointerDownPredicate = function (mesh) {
  25319. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25320. };
  25321. }
  25322. // Meshes
  25323. _this._pickedDownMesh = null;
  25324. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25325. _this._processPointerDown(pickResult, evt);
  25326. // Sprites
  25327. _this._pickedDownSprite = null;
  25328. if (_this.spriteManagers.length > 0) {
  25329. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25330. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25331. if (pickResult.pickedSprite.actionManager) {
  25332. _this._pickedDownSprite = pickResult.pickedSprite;
  25333. switch (evt.button) {
  25334. case 0:
  25335. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25336. break;
  25337. case 1:
  25338. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25339. break;
  25340. case 2:
  25341. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25342. break;
  25343. }
  25344. if (pickResult.pickedSprite.actionManager) {
  25345. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25346. }
  25347. }
  25348. }
  25349. }
  25350. };
  25351. this._onPointerUp = function (evt) {
  25352. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25353. return; // So we need to test it the pointer down was pressed before.
  25354. }
  25355. _this._totalPointersPressed--;
  25356. _this._pickedUpMesh = null;
  25357. _this._meshPickProceed = false;
  25358. _this._updatePointerPosition(evt);
  25359. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25360. // PreObservable support
  25361. if (_this.onPrePointerObservable.hasObservers()) {
  25362. if (!clickInfo.ignore) {
  25363. if (!clickInfo.hasSwiped) {
  25364. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25365. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25366. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25367. _this.onPrePointerObservable.notifyObservers(pi, type);
  25368. if (pi.skipOnPointerObservable) {
  25369. return;
  25370. }
  25371. }
  25372. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25373. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25374. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25375. _this.onPrePointerObservable.notifyObservers(pi, type);
  25376. if (pi.skipOnPointerObservable) {
  25377. return;
  25378. }
  25379. }
  25380. }
  25381. }
  25382. else {
  25383. var type = BABYLON.PointerEventTypes.POINTERUP;
  25384. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25385. _this.onPrePointerObservable.notifyObservers(pi, type);
  25386. if (pi.skipOnPointerObservable) {
  25387. return;
  25388. }
  25389. }
  25390. }
  25391. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25392. return;
  25393. }
  25394. _this._pointerCaptures[evt.pointerId] = false;
  25395. if (!_this.pointerUpPredicate) {
  25396. _this.pointerUpPredicate = function (mesh) {
  25397. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25398. };
  25399. }
  25400. // Meshes
  25401. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25402. _this._initActionManager(null, clickInfo);
  25403. }
  25404. if (!pickResult) {
  25405. pickResult = _this._currentPickResult;
  25406. }
  25407. _this._processPointerUp(pickResult, evt, clickInfo);
  25408. // Sprites
  25409. if (!clickInfo.ignore) {
  25410. if (_this.spriteManagers.length > 0) {
  25411. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25412. if (spritePickResult) {
  25413. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25414. if (spritePickResult.pickedSprite.actionManager) {
  25415. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25416. if (spritePickResult.pickedSprite.actionManager) {
  25417. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25418. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25419. }
  25420. }
  25421. }
  25422. }
  25423. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25424. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25425. }
  25426. }
  25427. }
  25428. }
  25429. _this._previousPickResult = _this._currentPickResult;
  25430. });
  25431. };
  25432. this._onKeyDown = function (evt) {
  25433. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25434. if (_this.onPreKeyboardObservable.hasObservers()) {
  25435. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25436. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25437. if (pi.skipOnPointerObservable) {
  25438. return;
  25439. }
  25440. }
  25441. if (_this.onKeyboardObservable.hasObservers()) {
  25442. var pi = new BABYLON.KeyboardInfo(type, evt);
  25443. _this.onKeyboardObservable.notifyObservers(pi, type);
  25444. }
  25445. if (_this.actionManager) {
  25446. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25447. }
  25448. };
  25449. this._onKeyUp = function (evt) {
  25450. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25451. if (_this.onPreKeyboardObservable.hasObservers()) {
  25452. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25453. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25454. if (pi.skipOnPointerObservable) {
  25455. return;
  25456. }
  25457. }
  25458. if (_this.onKeyboardObservable.hasObservers()) {
  25459. var pi = new BABYLON.KeyboardInfo(type, evt);
  25460. _this.onKeyboardObservable.notifyObservers(pi, type);
  25461. }
  25462. if (_this.actionManager) {
  25463. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25464. }
  25465. };
  25466. var engine = this.getEngine();
  25467. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25468. if (!canvas) {
  25469. return;
  25470. }
  25471. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25472. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25473. });
  25474. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25475. if (!canvas) {
  25476. return;
  25477. }
  25478. canvas.removeEventListener("keydown", _this._onKeyDown);
  25479. canvas.removeEventListener("keyup", _this._onKeyUp);
  25480. });
  25481. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25482. var canvas = this._engine.getRenderingCanvas();
  25483. if (!canvas) {
  25484. return;
  25485. }
  25486. if (attachMove) {
  25487. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25488. // Wheel
  25489. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25490. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25491. }
  25492. if (attachDown) {
  25493. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25494. }
  25495. if (attachUp) {
  25496. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25497. }
  25498. canvas.tabIndex = 1;
  25499. };
  25500. /** Detaches all event handlers*/
  25501. Scene.prototype.detachControl = function () {
  25502. var engine = this.getEngine();
  25503. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25504. var canvas = engine.getRenderingCanvas();
  25505. if (!canvas) {
  25506. return;
  25507. }
  25508. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25509. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25510. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25511. if (this._onCanvasBlurObserver) {
  25512. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25513. }
  25514. if (this._onCanvasFocusObserver) {
  25515. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25516. }
  25517. // Wheel
  25518. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25519. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25520. // Keyboard
  25521. canvas.removeEventListener("keydown", this._onKeyDown);
  25522. canvas.removeEventListener("keyup", this._onKeyUp);
  25523. // Observables
  25524. this.onKeyboardObservable.clear();
  25525. this.onPreKeyboardObservable.clear();
  25526. this.onPointerObservable.clear();
  25527. this.onPrePointerObservable.clear();
  25528. };
  25529. /**
  25530. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25531. * Delay loaded resources are not taking in account
  25532. * @return true if all required resources are ready
  25533. */
  25534. Scene.prototype.isReady = function () {
  25535. if (this._isDisposed) {
  25536. return false;
  25537. }
  25538. if (this._pendingData.length > 0) {
  25539. return false;
  25540. }
  25541. var index;
  25542. var engine = this.getEngine();
  25543. // Geometries
  25544. for (index = 0; index < this._geometries.length; index++) {
  25545. var geometry = this._geometries[index];
  25546. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25547. return false;
  25548. }
  25549. }
  25550. // Meshes
  25551. for (index = 0; index < this.meshes.length; index++) {
  25552. var mesh = this.meshes[index];
  25553. if (!mesh.isEnabled()) {
  25554. continue;
  25555. }
  25556. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25557. continue;
  25558. }
  25559. if (!mesh.isReady(true)) {
  25560. return false;
  25561. }
  25562. // Effect layers
  25563. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25564. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25565. var layer = _a[_i];
  25566. if (!layer.hasMesh(mesh)) {
  25567. continue;
  25568. }
  25569. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25570. var subMesh = _c[_b];
  25571. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25572. return false;
  25573. }
  25574. }
  25575. }
  25576. }
  25577. // Post-processes
  25578. if (this.activeCameras && this.activeCameras.length > 0) {
  25579. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25580. var camera = _e[_d];
  25581. if (!camera.isReady(true)) {
  25582. return false;
  25583. }
  25584. }
  25585. }
  25586. else if (this.activeCamera) {
  25587. if (!this.activeCamera.isReady(true)) {
  25588. return false;
  25589. }
  25590. }
  25591. // Particles
  25592. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25593. var particleSystem = _g[_f];
  25594. if (!particleSystem.isReady()) {
  25595. return false;
  25596. }
  25597. }
  25598. return true;
  25599. };
  25600. /** Resets all cached information relative to material (including effect and visibility) */
  25601. Scene.prototype.resetCachedMaterial = function () {
  25602. this._cachedMaterial = null;
  25603. this._cachedEffect = null;
  25604. this._cachedVisibility = null;
  25605. };
  25606. /**
  25607. * Registers a function to be called before every frame render
  25608. * @param func defines the function to register
  25609. */
  25610. Scene.prototype.registerBeforeRender = function (func) {
  25611. this.onBeforeRenderObservable.add(func);
  25612. };
  25613. /**
  25614. * Unregisters a function called before every frame render
  25615. * @param func defines the function to unregister
  25616. */
  25617. Scene.prototype.unregisterBeforeRender = function (func) {
  25618. this.onBeforeRenderObservable.removeCallback(func);
  25619. };
  25620. /**
  25621. * Registers a function to be called after every frame render
  25622. * @param func defines the function to register
  25623. */
  25624. Scene.prototype.registerAfterRender = function (func) {
  25625. this.onAfterRenderObservable.add(func);
  25626. };
  25627. /**
  25628. * Unregisters a function called after every frame render
  25629. * @param func defines the function to unregister
  25630. */
  25631. Scene.prototype.unregisterAfterRender = function (func) {
  25632. this.onAfterRenderObservable.removeCallback(func);
  25633. };
  25634. Scene.prototype._executeOnceBeforeRender = function (func) {
  25635. var _this = this;
  25636. var execFunc = function () {
  25637. func();
  25638. setTimeout(function () {
  25639. _this.unregisterBeforeRender(execFunc);
  25640. });
  25641. };
  25642. this.registerBeforeRender(execFunc);
  25643. };
  25644. /**
  25645. * The provided function will run before render once and will be disposed afterwards.
  25646. * A timeout delay can be provided so that the function will be executed in N ms.
  25647. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25648. * @param func The function to be executed.
  25649. * @param timeout optional delay in ms
  25650. */
  25651. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25652. var _this = this;
  25653. if (timeout !== undefined) {
  25654. setTimeout(function () {
  25655. _this._executeOnceBeforeRender(func);
  25656. }, timeout);
  25657. }
  25658. else {
  25659. this._executeOnceBeforeRender(func);
  25660. }
  25661. };
  25662. /** @hidden */
  25663. Scene.prototype._addPendingData = function (data) {
  25664. this._pendingData.push(data);
  25665. };
  25666. /** @hidden */
  25667. Scene.prototype._removePendingData = function (data) {
  25668. var wasLoading = this.isLoading;
  25669. var index = this._pendingData.indexOf(data);
  25670. if (index !== -1) {
  25671. this._pendingData.splice(index, 1);
  25672. }
  25673. if (wasLoading && !this.isLoading) {
  25674. this.onDataLoadedObservable.notifyObservers(this);
  25675. }
  25676. };
  25677. /**
  25678. * Returns the number of items waiting to be loaded
  25679. * @returns the number of items waiting to be loaded
  25680. */
  25681. Scene.prototype.getWaitingItemsCount = function () {
  25682. return this._pendingData.length;
  25683. };
  25684. Object.defineProperty(Scene.prototype, "isLoading", {
  25685. /**
  25686. * Returns a boolean indicating if the scene is still loading data
  25687. */
  25688. get: function () {
  25689. return this._pendingData.length > 0;
  25690. },
  25691. enumerable: true,
  25692. configurable: true
  25693. });
  25694. /**
  25695. * Registers a function to be executed when the scene is ready
  25696. * @param {Function} func - the function to be executed
  25697. */
  25698. Scene.prototype.executeWhenReady = function (func) {
  25699. var _this = this;
  25700. this.onReadyObservable.add(func);
  25701. if (this._executeWhenReadyTimeoutId !== -1) {
  25702. return;
  25703. }
  25704. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25705. _this._checkIsReady();
  25706. }, 150);
  25707. };
  25708. /**
  25709. * Returns a promise that resolves when the scene is ready
  25710. * @returns A promise that resolves when the scene is ready
  25711. */
  25712. Scene.prototype.whenReadyAsync = function () {
  25713. var _this = this;
  25714. return new Promise(function (resolve) {
  25715. _this.executeWhenReady(function () {
  25716. resolve();
  25717. });
  25718. });
  25719. };
  25720. /** @hidden */
  25721. Scene.prototype._checkIsReady = function () {
  25722. var _this = this;
  25723. if (this.isReady()) {
  25724. this.onReadyObservable.notifyObservers(this);
  25725. this.onReadyObservable.clear();
  25726. this._executeWhenReadyTimeoutId = -1;
  25727. return;
  25728. }
  25729. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25730. _this._checkIsReady();
  25731. }, 150);
  25732. };
  25733. // Animations
  25734. /**
  25735. * Will start the animation sequence of a given target
  25736. * @param target defines the target
  25737. * @param from defines from which frame should animation start
  25738. * @param to defines until which frame should animation run.
  25739. * @param weight defines the weight to apply to the animation (1.0 by default)
  25740. * @param loop defines if the animation loops
  25741. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25742. * @param onAnimationEnd defines the function to be executed when the animation ends
  25743. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25744. * @returns the animatable object created for this animation
  25745. */
  25746. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25747. if (weight === void 0) { weight = 1.0; }
  25748. if (speedRatio === void 0) { speedRatio = 1.0; }
  25749. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25750. returnedAnimatable.weight = weight;
  25751. return returnedAnimatable;
  25752. };
  25753. /**
  25754. * Will start the animation sequence of a given target
  25755. * @param target defines the target
  25756. * @param from defines from which frame should animation start
  25757. * @param to defines until which frame should animation run.
  25758. * @param loop defines if the animation loops
  25759. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25760. * @param onAnimationEnd defines the function to be executed when the animation ends
  25761. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25762. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25763. * @returns the animatable object created for this animation
  25764. */
  25765. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25766. if (speedRatio === void 0) { speedRatio = 1.0; }
  25767. if (stopCurrent === void 0) { stopCurrent = true; }
  25768. if (from > to && speedRatio > 0) {
  25769. speedRatio *= -1;
  25770. }
  25771. if (stopCurrent) {
  25772. this.stopAnimation(target);
  25773. }
  25774. if (!animatable) {
  25775. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25776. }
  25777. // Local animations
  25778. if (target.animations) {
  25779. animatable.appendAnimations(target, target.animations);
  25780. }
  25781. // Children animations
  25782. if (target.getAnimatables) {
  25783. var animatables = target.getAnimatables();
  25784. for (var index = 0; index < animatables.length; index++) {
  25785. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25786. }
  25787. }
  25788. animatable.reset();
  25789. return animatable;
  25790. };
  25791. /**
  25792. * Begin a new animation on a given node
  25793. * @param target defines the target where the animation will take place
  25794. * @param animations defines the list of animations to start
  25795. * @param from defines the initial value
  25796. * @param to defines the final value
  25797. * @param loop defines if you want animation to loop (off by default)
  25798. * @param speedRatio defines the speed ratio to apply to all animations
  25799. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25800. * @returns the list of created animatables
  25801. */
  25802. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25803. if (speedRatio === undefined) {
  25804. speedRatio = 1.0;
  25805. }
  25806. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25807. return animatable;
  25808. };
  25809. /**
  25810. * Begin a new animation on a given node and its hierarchy
  25811. * @param target defines the root node where the animation will take place
  25812. * @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.
  25813. * @param animations defines the list of animations to start
  25814. * @param from defines the initial value
  25815. * @param to defines the final value
  25816. * @param loop defines if you want animation to loop (off by default)
  25817. * @param speedRatio defines the speed ratio to apply to all animations
  25818. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25819. * @returns the list of animatables created for all nodes
  25820. */
  25821. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25822. var children = target.getDescendants(directDescendantsOnly);
  25823. var result = [];
  25824. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25825. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25826. var child = children_1[_i];
  25827. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25828. }
  25829. return result;
  25830. };
  25831. /**
  25832. * Gets the animatable associated with a specific target
  25833. * @param target defines the target of the animatable
  25834. * @returns the required animatable if found
  25835. */
  25836. Scene.prototype.getAnimatableByTarget = function (target) {
  25837. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25838. if (this._activeAnimatables[index].target === target) {
  25839. return this._activeAnimatables[index];
  25840. }
  25841. }
  25842. return null;
  25843. };
  25844. /**
  25845. * Gets all animatables associated with a given target
  25846. * @param target defines the target to look animatables for
  25847. * @returns an array of Animatables
  25848. */
  25849. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25850. var result = [];
  25851. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25852. if (this._activeAnimatables[index].target === target) {
  25853. result.push(this._activeAnimatables[index]);
  25854. }
  25855. }
  25856. return result;
  25857. };
  25858. Object.defineProperty(Scene.prototype, "animatables", {
  25859. /**
  25860. * Gets all animatable attached to the scene
  25861. */
  25862. get: function () {
  25863. return this._activeAnimatables;
  25864. },
  25865. enumerable: true,
  25866. configurable: true
  25867. });
  25868. /**
  25869. * Will stop the animation of the given target
  25870. * @param target - the target
  25871. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25872. */
  25873. Scene.prototype.stopAnimation = function (target, animationName) {
  25874. var animatables = this.getAllAnimatablesByTarget(target);
  25875. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25876. var animatable = animatables_1[_i];
  25877. animatable.stop(animationName);
  25878. }
  25879. };
  25880. /**
  25881. * Stops and removes all animations that have been applied to the scene
  25882. */
  25883. Scene.prototype.stopAllAnimations = function () {
  25884. if (this._activeAnimatables) {
  25885. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25886. this._activeAnimatables[i].stop();
  25887. }
  25888. this._activeAnimatables = [];
  25889. }
  25890. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25891. var group = _a[_i];
  25892. group.stop();
  25893. }
  25894. };
  25895. Scene.prototype._animate = function () {
  25896. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25897. return;
  25898. }
  25899. // Getting time
  25900. var now = BABYLON.Tools.Now;
  25901. if (!this._animationTimeLast) {
  25902. if (this._pendingData.length > 0) {
  25903. return;
  25904. }
  25905. this._animationTimeLast = now;
  25906. }
  25907. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25908. this._animationTime += deltaTime;
  25909. this._animationTimeLast = now;
  25910. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25911. this._activeAnimatables[index]._animate(this._animationTime);
  25912. }
  25913. // Late animation bindings
  25914. this._processLateAnimationBindings();
  25915. };
  25916. /** @hidden */
  25917. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25918. var target = runtimeAnimation.target;
  25919. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25920. if (!target._lateAnimationHolders) {
  25921. target._lateAnimationHolders = {};
  25922. }
  25923. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25924. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25925. totalWeight: 0,
  25926. animations: [],
  25927. originalValue: originalValue
  25928. };
  25929. }
  25930. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25931. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25932. };
  25933. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25934. var normalizer = 1.0;
  25935. var finalPosition = BABYLON.Tmp.Vector3[0];
  25936. var finalScaling = BABYLON.Tmp.Vector3[1];
  25937. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25938. var startIndex = 0;
  25939. var originalAnimation = holder.animations[0];
  25940. var originalValue = holder.originalValue;
  25941. var scale = 1;
  25942. if (holder.totalWeight < 1.0) {
  25943. // We need to mix the original value in
  25944. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25945. scale = 1.0 - holder.totalWeight;
  25946. }
  25947. else {
  25948. startIndex = 1;
  25949. // We need to normalize the weights
  25950. normalizer = holder.totalWeight;
  25951. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25952. scale = originalAnimation.weight / normalizer;
  25953. if (scale == 1) {
  25954. return originalAnimation.currentValue;
  25955. }
  25956. }
  25957. finalScaling.scaleInPlace(scale);
  25958. finalPosition.scaleInPlace(scale);
  25959. finalQuaternion.scaleInPlace(scale);
  25960. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25961. var runtimeAnimation = holder.animations[animIndex];
  25962. var scale = runtimeAnimation.weight / normalizer;
  25963. var currentPosition = BABYLON.Tmp.Vector3[2];
  25964. var currentScaling = BABYLON.Tmp.Vector3[3];
  25965. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25966. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25967. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25968. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25969. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25970. }
  25971. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25972. return originalAnimation._workValue;
  25973. };
  25974. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25975. var originalAnimation = holder.animations[0];
  25976. var originalValue = holder.originalValue;
  25977. if (holder.animations.length === 1) {
  25978. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25979. }
  25980. var normalizer = 1.0;
  25981. var quaternions;
  25982. var weights;
  25983. if (holder.totalWeight < 1.0) {
  25984. var scale = 1.0 - holder.totalWeight;
  25985. quaternions = [];
  25986. weights = [];
  25987. quaternions.push(originalValue);
  25988. weights.push(scale);
  25989. }
  25990. else {
  25991. if (holder.animations.length === 2) { // Slerp as soon as we can
  25992. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25993. }
  25994. quaternions = [];
  25995. weights = [];
  25996. normalizer = holder.totalWeight;
  25997. }
  25998. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25999. var runtimeAnimation = holder.animations[animIndex];
  26000. quaternions.push(runtimeAnimation.currentValue);
  26001. weights.push(runtimeAnimation.weight / normalizer);
  26002. }
  26003. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26004. var cumulativeAmount = 0;
  26005. var cumulativeQuaternion = null;
  26006. for (var index = 0; index < quaternions.length;) {
  26007. if (!cumulativeQuaternion) {
  26008. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26009. cumulativeAmount = weights[index] + weights[index + 1];
  26010. index += 2;
  26011. continue;
  26012. }
  26013. cumulativeAmount += weights[index];
  26014. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26015. index++;
  26016. }
  26017. return cumulativeQuaternion;
  26018. };
  26019. Scene.prototype._processLateAnimationBindings = function () {
  26020. if (!this._registeredForLateAnimationBindings.length) {
  26021. return;
  26022. }
  26023. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26024. var target = this._registeredForLateAnimationBindings.data[index];
  26025. for (var path in target._lateAnimationHolders) {
  26026. var holder = target._lateAnimationHolders[path];
  26027. var originalAnimation = holder.animations[0];
  26028. var originalValue = holder.originalValue;
  26029. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26030. var finalValue = void 0;
  26031. if (matrixDecomposeMode) {
  26032. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26033. }
  26034. else {
  26035. var quaternionMode = originalValue.w !== undefined;
  26036. if (quaternionMode) {
  26037. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26038. }
  26039. else {
  26040. var startIndex = 0;
  26041. var normalizer = 1.0;
  26042. if (holder.totalWeight < 1.0) {
  26043. // We need to mix the original value in
  26044. if (originalValue.scale) {
  26045. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26046. }
  26047. else {
  26048. finalValue = originalValue * (1.0 - holder.totalWeight);
  26049. }
  26050. }
  26051. else {
  26052. // We need to normalize the weights
  26053. normalizer = holder.totalWeight;
  26054. var scale_1 = originalAnimation.weight / normalizer;
  26055. if (scale_1 !== 1) {
  26056. if (originalAnimation.currentValue.scale) {
  26057. finalValue = originalAnimation.currentValue.scale(scale_1);
  26058. }
  26059. else {
  26060. finalValue = originalAnimation.currentValue * scale_1;
  26061. }
  26062. }
  26063. else {
  26064. finalValue = originalAnimation.currentValue;
  26065. }
  26066. startIndex = 1;
  26067. }
  26068. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26069. var runtimeAnimation = holder.animations[animIndex];
  26070. var scale = runtimeAnimation.weight / normalizer;
  26071. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26072. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26073. }
  26074. else {
  26075. finalValue += runtimeAnimation.currentValue * scale;
  26076. }
  26077. }
  26078. }
  26079. }
  26080. target[path] = finalValue;
  26081. }
  26082. target._lateAnimationHolders = {};
  26083. }
  26084. this._registeredForLateAnimationBindings.reset();
  26085. };
  26086. // Matrix
  26087. /** @hidden */
  26088. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26089. this._useAlternateCameraConfiguration = active;
  26090. };
  26091. /**
  26092. * Gets the current view matrix
  26093. * @returns a Matrix
  26094. */
  26095. Scene.prototype.getViewMatrix = function () {
  26096. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26097. };
  26098. /**
  26099. * Gets the current projection matrix
  26100. * @returns a Matrix
  26101. */
  26102. Scene.prototype.getProjectionMatrix = function () {
  26103. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26104. };
  26105. /**
  26106. * Gets the current transform matrix
  26107. * @returns a Matrix made of View * Projection
  26108. */
  26109. Scene.prototype.getTransformMatrix = function () {
  26110. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26111. };
  26112. /**
  26113. * Sets the current transform matrix
  26114. * @param view defines the View matrix to use
  26115. * @param projection defines the Projection matrix to use
  26116. */
  26117. Scene.prototype.setTransformMatrix = function (view, projection) {
  26118. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26119. return;
  26120. }
  26121. this._viewUpdateFlag = view.updateFlag;
  26122. this._projectionUpdateFlag = projection.updateFlag;
  26123. this._viewMatrix = view;
  26124. this._projectionMatrix = projection;
  26125. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26126. // Update frustum
  26127. if (!this._frustumPlanes) {
  26128. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26129. }
  26130. else {
  26131. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26132. }
  26133. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26134. var otherCamera = this.activeCamera._alternateCamera;
  26135. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26136. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26137. }
  26138. if (this._sceneUbo.useUbo) {
  26139. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26140. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26141. this._sceneUbo.update();
  26142. }
  26143. };
  26144. /** @hidden */
  26145. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26146. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26147. return;
  26148. }
  26149. this._alternateViewUpdateFlag = view.updateFlag;
  26150. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26151. this._alternateViewMatrix = view;
  26152. this._alternateProjectionMatrix = projection;
  26153. if (!this._alternateTransformMatrix) {
  26154. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26155. }
  26156. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26157. if (!this._alternateSceneUbo) {
  26158. this._createAlternateUbo();
  26159. }
  26160. if (this._alternateSceneUbo.useUbo) {
  26161. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26162. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26163. this._alternateSceneUbo.update();
  26164. }
  26165. };
  26166. /**
  26167. * Gets the uniform buffer used to store scene data
  26168. * @returns a UniformBuffer
  26169. */
  26170. Scene.prototype.getSceneUniformBuffer = function () {
  26171. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26172. };
  26173. /**
  26174. * Gets an unique (relatively to the current scene) Id
  26175. * @returns an unique number for the scene
  26176. */
  26177. Scene.prototype.getUniqueId = function () {
  26178. var result = Scene._uniqueIdCounter;
  26179. Scene._uniqueIdCounter++;
  26180. return result;
  26181. };
  26182. /**
  26183. * Add a mesh to the list of scene's meshes
  26184. * @param newMesh defines the mesh to add
  26185. * @param recursive if all child meshes should also be added to the scene
  26186. */
  26187. Scene.prototype.addMesh = function (newMesh, recursive) {
  26188. var _this = this;
  26189. if (recursive === void 0) { recursive = false; }
  26190. this.meshes.push(newMesh);
  26191. //notify the collision coordinator
  26192. if (this.collisionCoordinator) {
  26193. this.collisionCoordinator.onMeshAdded(newMesh);
  26194. }
  26195. newMesh._resyncLightSources();
  26196. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26197. if (recursive) {
  26198. newMesh.getChildMeshes().forEach(function (m) {
  26199. _this.addMesh(m);
  26200. });
  26201. }
  26202. };
  26203. /**
  26204. * Remove a mesh for the list of scene's meshes
  26205. * @param toRemove defines the mesh to remove
  26206. * @param recursive if all child meshes should also be removed from the scene
  26207. * @returns the index where the mesh was in the mesh list
  26208. */
  26209. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26210. var _this = this;
  26211. if (recursive === void 0) { recursive = false; }
  26212. var index = this.meshes.indexOf(toRemove);
  26213. if (index !== -1) {
  26214. // Remove from the scene if mesh found
  26215. this.meshes.splice(index, 1);
  26216. }
  26217. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26218. if (recursive) {
  26219. toRemove.getChildMeshes().forEach(function (m) {
  26220. _this.removeMesh(m);
  26221. });
  26222. }
  26223. return index;
  26224. };
  26225. /**
  26226. * Add a transform node to the list of scene's transform nodes
  26227. * @param newTransformNode defines the transform node to add
  26228. */
  26229. Scene.prototype.addTransformNode = function (newTransformNode) {
  26230. this.transformNodes.push(newTransformNode);
  26231. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26232. };
  26233. /**
  26234. * Remove a transform node for the list of scene's transform nodes
  26235. * @param toRemove defines the transform node to remove
  26236. * @returns the index where the transform node was in the transform node list
  26237. */
  26238. Scene.prototype.removeTransformNode = function (toRemove) {
  26239. var index = this.transformNodes.indexOf(toRemove);
  26240. if (index !== -1) {
  26241. // Remove from the scene if found
  26242. this.transformNodes.splice(index, 1);
  26243. }
  26244. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26245. return index;
  26246. };
  26247. /**
  26248. * Remove a skeleton for the list of scene's skeletons
  26249. * @param toRemove defines the skeleton to remove
  26250. * @returns the index where the skeleton was in the skeleton list
  26251. */
  26252. Scene.prototype.removeSkeleton = function (toRemove) {
  26253. var index = this.skeletons.indexOf(toRemove);
  26254. if (index !== -1) {
  26255. // Remove from the scene if found
  26256. this.skeletons.splice(index, 1);
  26257. }
  26258. return index;
  26259. };
  26260. /**
  26261. * Remove a morph target for the list of scene's morph targets
  26262. * @param toRemove defines the morph target to remove
  26263. * @returns the index where the morph target was in the morph target list
  26264. */
  26265. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26266. var index = this.morphTargetManagers.indexOf(toRemove);
  26267. if (index !== -1) {
  26268. // Remove from the scene if found
  26269. this.morphTargetManagers.splice(index, 1);
  26270. }
  26271. return index;
  26272. };
  26273. /**
  26274. * Remove a light for the list of scene's lights
  26275. * @param toRemove defines the light to remove
  26276. * @returns the index where the light was in the light list
  26277. */
  26278. Scene.prototype.removeLight = function (toRemove) {
  26279. var index = this.lights.indexOf(toRemove);
  26280. if (index !== -1) {
  26281. // Remove from meshes
  26282. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26283. var mesh = _a[_i];
  26284. mesh._removeLightSource(toRemove);
  26285. }
  26286. // Remove from the scene if mesh found
  26287. this.lights.splice(index, 1);
  26288. this.sortLightsByPriority();
  26289. }
  26290. this.onLightRemovedObservable.notifyObservers(toRemove);
  26291. return index;
  26292. };
  26293. /**
  26294. * Remove a camera for the list of scene's cameras
  26295. * @param toRemove defines the camera to remove
  26296. * @returns the index where the camera was in the camera list
  26297. */
  26298. Scene.prototype.removeCamera = function (toRemove) {
  26299. var index = this.cameras.indexOf(toRemove);
  26300. if (index !== -1) {
  26301. // Remove from the scene if mesh found
  26302. this.cameras.splice(index, 1);
  26303. }
  26304. // Remove from activeCameras
  26305. var index2 = this.activeCameras.indexOf(toRemove);
  26306. if (index2 !== -1) {
  26307. // Remove from the scene if mesh found
  26308. this.activeCameras.splice(index2, 1);
  26309. }
  26310. // Reset the activeCamera
  26311. if (this.activeCamera === toRemove) {
  26312. if (this.cameras.length > 0) {
  26313. this.activeCamera = this.cameras[0];
  26314. }
  26315. else {
  26316. this.activeCamera = null;
  26317. }
  26318. }
  26319. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26320. return index;
  26321. };
  26322. /**
  26323. * Remove a particle system for the list of scene's particle systems
  26324. * @param toRemove defines the particle system to remove
  26325. * @returns the index where the particle system was in the particle system list
  26326. */
  26327. Scene.prototype.removeParticleSystem = function (toRemove) {
  26328. var index = this.particleSystems.indexOf(toRemove);
  26329. if (index !== -1) {
  26330. this.particleSystems.splice(index, 1);
  26331. }
  26332. return index;
  26333. };
  26334. /**
  26335. * Remove a animation for the list of scene's animations
  26336. * @param toRemove defines the animation to remove
  26337. * @returns the index where the animation was in the animation list
  26338. */
  26339. Scene.prototype.removeAnimation = function (toRemove) {
  26340. var index = this.animations.indexOf(toRemove);
  26341. if (index !== -1) {
  26342. this.animations.splice(index, 1);
  26343. }
  26344. return index;
  26345. };
  26346. /**
  26347. * Removes the given animation group from this scene.
  26348. * @param toRemove The animation group to remove
  26349. * @returns The index of the removed animation group
  26350. */
  26351. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26352. var index = this.animationGroups.indexOf(toRemove);
  26353. if (index !== -1) {
  26354. this.animationGroups.splice(index, 1);
  26355. }
  26356. return index;
  26357. };
  26358. /**
  26359. * Removes the given multi-material from this scene.
  26360. * @param toRemove The multi-material to remove
  26361. * @returns The index of the removed multi-material
  26362. */
  26363. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26364. var index = this.multiMaterials.indexOf(toRemove);
  26365. if (index !== -1) {
  26366. this.multiMaterials.splice(index, 1);
  26367. }
  26368. return index;
  26369. };
  26370. /**
  26371. * Removes the given material from this scene.
  26372. * @param toRemove The material to remove
  26373. * @returns The index of the removed material
  26374. */
  26375. Scene.prototype.removeMaterial = function (toRemove) {
  26376. var index = this.materials.indexOf(toRemove);
  26377. if (index !== -1) {
  26378. this.materials.splice(index, 1);
  26379. }
  26380. return index;
  26381. };
  26382. /**
  26383. * Removes the given lens flare system from this scene.
  26384. * @param toRemove The lens flare system to remove
  26385. * @returns The index of the removed lens flare system
  26386. */
  26387. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26388. var index = this.lensFlareSystems.indexOf(toRemove);
  26389. if (index !== -1) {
  26390. this.lensFlareSystems.splice(index, 1);
  26391. }
  26392. return index;
  26393. };
  26394. /**
  26395. * Removes the given action manager from this scene.
  26396. * @param toRemove The action manager to remove
  26397. * @returns The index of the removed action manager
  26398. */
  26399. Scene.prototype.removeActionManager = function (toRemove) {
  26400. var index = this._actionManagers.indexOf(toRemove);
  26401. if (index !== -1) {
  26402. this._actionManagers.splice(index, 1);
  26403. }
  26404. return index;
  26405. };
  26406. /**
  26407. * Removes the given effect layer from this scene.
  26408. * @param toRemove defines the effect layer to remove
  26409. * @returns the index of the removed effect layer
  26410. */
  26411. Scene.prototype.removeEffectLayer = function (toRemove) {
  26412. var index = this.effectLayers.indexOf(toRemove);
  26413. if (index !== -1) {
  26414. this.effectLayers.splice(index, 1);
  26415. }
  26416. return index;
  26417. };
  26418. /**
  26419. * Removes the given texture from this scene.
  26420. * @param toRemove The texture to remove
  26421. * @returns The index of the removed texture
  26422. */
  26423. Scene.prototype.removeTexture = function (toRemove) {
  26424. var index = this.textures.indexOf(toRemove);
  26425. if (index !== -1) {
  26426. this.textures.splice(index, 1);
  26427. }
  26428. return index;
  26429. };
  26430. /**
  26431. * Adds the given light to this scene
  26432. * @param newLight The light to add
  26433. */
  26434. Scene.prototype.addLight = function (newLight) {
  26435. this.lights.push(newLight);
  26436. this.sortLightsByPriority();
  26437. // Add light to all meshes (To support if the light is removed and then readded)
  26438. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26439. var mesh = _a[_i];
  26440. if (mesh._lightSources.indexOf(newLight) === -1) {
  26441. mesh._lightSources.push(newLight);
  26442. mesh._resyncLightSources();
  26443. }
  26444. }
  26445. this.onNewLightAddedObservable.notifyObservers(newLight);
  26446. };
  26447. /**
  26448. * Sorts the list list based on light priorities
  26449. */
  26450. Scene.prototype.sortLightsByPriority = function () {
  26451. if (this.requireLightSorting) {
  26452. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26453. }
  26454. };
  26455. /**
  26456. * Adds the given camera to this scene
  26457. * @param newCamera The camera to add
  26458. */
  26459. Scene.prototype.addCamera = function (newCamera) {
  26460. this.cameras.push(newCamera);
  26461. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26462. };
  26463. /**
  26464. * Adds the given skeleton to this scene
  26465. * @param newSkeleton The skeleton to add
  26466. */
  26467. Scene.prototype.addSkeleton = function (newSkeleton) {
  26468. this.skeletons.push(newSkeleton);
  26469. };
  26470. /**
  26471. * Adds the given particle system to this scene
  26472. * @param newParticleSystem The particle system to add
  26473. */
  26474. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26475. this.particleSystems.push(newParticleSystem);
  26476. };
  26477. /**
  26478. * Adds the given animation to this scene
  26479. * @param newAnimation The animation to add
  26480. */
  26481. Scene.prototype.addAnimation = function (newAnimation) {
  26482. this.animations.push(newAnimation);
  26483. };
  26484. /**
  26485. * Adds the given animation group to this scene.
  26486. * @param newAnimationGroup The animation group to add
  26487. */
  26488. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26489. this.animationGroups.push(newAnimationGroup);
  26490. };
  26491. /**
  26492. * Adds the given multi-material to this scene
  26493. * @param newMultiMaterial The multi-material to add
  26494. */
  26495. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26496. this.multiMaterials.push(newMultiMaterial);
  26497. };
  26498. /**
  26499. * Adds the given material to this scene
  26500. * @param newMaterial The material to add
  26501. */
  26502. Scene.prototype.addMaterial = function (newMaterial) {
  26503. this.materials.push(newMaterial);
  26504. };
  26505. /**
  26506. * Adds the given morph target to this scene
  26507. * @param newMorphTargetManager The morph target to add
  26508. */
  26509. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26510. this.morphTargetManagers.push(newMorphTargetManager);
  26511. };
  26512. /**
  26513. * Adds the given geometry to this scene
  26514. * @param newGeometry The geometry to add
  26515. */
  26516. Scene.prototype.addGeometry = function (newGeometry) {
  26517. this._geometries.push(newGeometry);
  26518. };
  26519. /**
  26520. * Adds the given lens flare system to this scene
  26521. * @param newLensFlareSystem The lens flare system to add
  26522. */
  26523. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26524. this.lensFlareSystems.push(newLensFlareSystem);
  26525. };
  26526. /**
  26527. * Adds the given effect layer to this scene
  26528. * @param newEffectLayer defines the effect layer to add
  26529. */
  26530. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26531. this.effectLayers.push(newEffectLayer);
  26532. };
  26533. /**
  26534. * Adds the given action manager to this scene
  26535. * @param newActionManager The action manager to add
  26536. */
  26537. Scene.prototype.addActionManager = function (newActionManager) {
  26538. this._actionManagers.push(newActionManager);
  26539. };
  26540. /**
  26541. * Adds the given texture to this scene.
  26542. * @param newTexture The texture to add
  26543. */
  26544. Scene.prototype.addTexture = function (newTexture) {
  26545. this.textures.push(newTexture);
  26546. };
  26547. /**
  26548. * Switch active camera
  26549. * @param newCamera defines the new active camera
  26550. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26551. */
  26552. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26553. if (attachControl === void 0) { attachControl = true; }
  26554. var canvas = this._engine.getRenderingCanvas();
  26555. if (!canvas) {
  26556. return;
  26557. }
  26558. if (this.activeCamera) {
  26559. this.activeCamera.detachControl(canvas);
  26560. }
  26561. this.activeCamera = newCamera;
  26562. if (attachControl) {
  26563. newCamera.attachControl(canvas);
  26564. }
  26565. };
  26566. /**
  26567. * sets the active camera of the scene using its ID
  26568. * @param id defines the camera's ID
  26569. * @return the new active camera or null if none found.
  26570. */
  26571. Scene.prototype.setActiveCameraByID = function (id) {
  26572. var camera = this.getCameraByID(id);
  26573. if (camera) {
  26574. this.activeCamera = camera;
  26575. return camera;
  26576. }
  26577. return null;
  26578. };
  26579. /**
  26580. * sets the active camera of the scene using its name
  26581. * @param name defines the camera's name
  26582. * @returns the new active camera or null if none found.
  26583. */
  26584. Scene.prototype.setActiveCameraByName = function (name) {
  26585. var camera = this.getCameraByName(name);
  26586. if (camera) {
  26587. this.activeCamera = camera;
  26588. return camera;
  26589. }
  26590. return null;
  26591. };
  26592. /**
  26593. * get an animation group using its name
  26594. * @param name defines the material's name
  26595. * @return the animation group or null if none found.
  26596. */
  26597. Scene.prototype.getAnimationGroupByName = function (name) {
  26598. for (var index = 0; index < this.animationGroups.length; index++) {
  26599. if (this.animationGroups[index].name === name) {
  26600. return this.animationGroups[index];
  26601. }
  26602. }
  26603. return null;
  26604. };
  26605. /**
  26606. * get a material using its id
  26607. * @param id defines the material's ID
  26608. * @return the material or null if none found.
  26609. */
  26610. Scene.prototype.getMaterialByID = function (id) {
  26611. for (var index = 0; index < this.materials.length; index++) {
  26612. if (this.materials[index].id === id) {
  26613. return this.materials[index];
  26614. }
  26615. }
  26616. return null;
  26617. };
  26618. /**
  26619. * Gets a material using its name
  26620. * @param name defines the material's name
  26621. * @return the material or null if none found.
  26622. */
  26623. Scene.prototype.getMaterialByName = function (name) {
  26624. for (var index = 0; index < this.materials.length; index++) {
  26625. if (this.materials[index].name === name) {
  26626. return this.materials[index];
  26627. }
  26628. }
  26629. return null;
  26630. };
  26631. /**
  26632. * Gets a lens flare system using its name
  26633. * @param name defines the name to look for
  26634. * @returns the lens flare system or null if not found
  26635. */
  26636. Scene.prototype.getLensFlareSystemByName = function (name) {
  26637. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26638. if (this.lensFlareSystems[index].name === name) {
  26639. return this.lensFlareSystems[index];
  26640. }
  26641. }
  26642. return null;
  26643. };
  26644. /**
  26645. * Gets a lens flare system using its id
  26646. * @param id defines the id to look for
  26647. * @returns the lens flare system or null if not found
  26648. */
  26649. Scene.prototype.getLensFlareSystemByID = function (id) {
  26650. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26651. if (this.lensFlareSystems[index].id === id) {
  26652. return this.lensFlareSystems[index];
  26653. }
  26654. }
  26655. return null;
  26656. };
  26657. /**
  26658. * Gets a camera using its id
  26659. * @param id defines the id to look for
  26660. * @returns the camera or null if not found
  26661. */
  26662. Scene.prototype.getCameraByID = function (id) {
  26663. for (var index = 0; index < this.cameras.length; index++) {
  26664. if (this.cameras[index].id === id) {
  26665. return this.cameras[index];
  26666. }
  26667. }
  26668. return null;
  26669. };
  26670. /**
  26671. * Gets a camera using its unique id
  26672. * @param uniqueId defines the unique id to look for
  26673. * @returns the camera or null if not found
  26674. */
  26675. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26676. for (var index = 0; index < this.cameras.length; index++) {
  26677. if (this.cameras[index].uniqueId === uniqueId) {
  26678. return this.cameras[index];
  26679. }
  26680. }
  26681. return null;
  26682. };
  26683. /**
  26684. * Gets a camera using its name
  26685. * @param name defines the camera's name
  26686. * @return the camera or null if none found.
  26687. */
  26688. Scene.prototype.getCameraByName = function (name) {
  26689. for (var index = 0; index < this.cameras.length; index++) {
  26690. if (this.cameras[index].name === name) {
  26691. return this.cameras[index];
  26692. }
  26693. }
  26694. return null;
  26695. };
  26696. /**
  26697. * Gets a bone using its id
  26698. * @param id defines the bone's id
  26699. * @return the bone or null if not found
  26700. */
  26701. Scene.prototype.getBoneByID = function (id) {
  26702. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26703. var skeleton = this.skeletons[skeletonIndex];
  26704. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26705. if (skeleton.bones[boneIndex].id === id) {
  26706. return skeleton.bones[boneIndex];
  26707. }
  26708. }
  26709. }
  26710. return null;
  26711. };
  26712. /**
  26713. * Gets a bone using its id
  26714. * @param name defines the bone's name
  26715. * @return the bone or null if not found
  26716. */
  26717. Scene.prototype.getBoneByName = function (name) {
  26718. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26719. var skeleton = this.skeletons[skeletonIndex];
  26720. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26721. if (skeleton.bones[boneIndex].name === name) {
  26722. return skeleton.bones[boneIndex];
  26723. }
  26724. }
  26725. }
  26726. return null;
  26727. };
  26728. /**
  26729. * Gets a light node using its name
  26730. * @param name defines the the light's name
  26731. * @return the light or null if none found.
  26732. */
  26733. Scene.prototype.getLightByName = function (name) {
  26734. for (var index = 0; index < this.lights.length; index++) {
  26735. if (this.lights[index].name === name) {
  26736. return this.lights[index];
  26737. }
  26738. }
  26739. return null;
  26740. };
  26741. /**
  26742. * Gets a light node using its id
  26743. * @param id defines the light's id
  26744. * @return the light or null if none found.
  26745. */
  26746. Scene.prototype.getLightByID = function (id) {
  26747. for (var index = 0; index < this.lights.length; index++) {
  26748. if (this.lights[index].id === id) {
  26749. return this.lights[index];
  26750. }
  26751. }
  26752. return null;
  26753. };
  26754. /**
  26755. * Gets a light node using its scene-generated unique ID
  26756. * @param uniqueId defines the light's unique id
  26757. * @return the light or null if none found.
  26758. */
  26759. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26760. for (var index = 0; index < this.lights.length; index++) {
  26761. if (this.lights[index].uniqueId === uniqueId) {
  26762. return this.lights[index];
  26763. }
  26764. }
  26765. return null;
  26766. };
  26767. /**
  26768. * Gets a particle system by id
  26769. * @param id defines the particle system id
  26770. * @return the corresponding system or null if none found
  26771. */
  26772. Scene.prototype.getParticleSystemByID = function (id) {
  26773. for (var index = 0; index < this.particleSystems.length; index++) {
  26774. if (this.particleSystems[index].id === id) {
  26775. return this.particleSystems[index];
  26776. }
  26777. }
  26778. return null;
  26779. };
  26780. /**
  26781. * Gets a geometry using its ID
  26782. * @param id defines the geometry's id
  26783. * @return the geometry or null if none found.
  26784. */
  26785. Scene.prototype.getGeometryByID = function (id) {
  26786. for (var index = 0; index < this._geometries.length; index++) {
  26787. if (this._geometries[index].id === id) {
  26788. return this._geometries[index];
  26789. }
  26790. }
  26791. return null;
  26792. };
  26793. /**
  26794. * Add a new geometry to this scene
  26795. * @param geometry defines the geometry to be added to the scene.
  26796. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26797. * @return a boolean defining if the geometry was added or not
  26798. */
  26799. Scene.prototype.pushGeometry = function (geometry, force) {
  26800. if (!force && this.getGeometryByID(geometry.id)) {
  26801. return false;
  26802. }
  26803. this._geometries.push(geometry);
  26804. //notify the collision coordinator
  26805. if (this.collisionCoordinator) {
  26806. this.collisionCoordinator.onGeometryAdded(geometry);
  26807. }
  26808. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26809. return true;
  26810. };
  26811. /**
  26812. * Removes an existing geometry
  26813. * @param geometry defines the geometry to be removed from the scene
  26814. * @return a boolean defining if the geometry was removed or not
  26815. */
  26816. Scene.prototype.removeGeometry = function (geometry) {
  26817. var index = this._geometries.indexOf(geometry);
  26818. if (index > -1) {
  26819. this._geometries.splice(index, 1);
  26820. //notify the collision coordinator
  26821. if (this.collisionCoordinator) {
  26822. this.collisionCoordinator.onGeometryDeleted(geometry);
  26823. }
  26824. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26825. return true;
  26826. }
  26827. return false;
  26828. };
  26829. /**
  26830. * Gets the list of geometries attached to the scene
  26831. * @returns an array of Geometry
  26832. */
  26833. Scene.prototype.getGeometries = function () {
  26834. return this._geometries;
  26835. };
  26836. /**
  26837. * Gets the first added mesh found of a given ID
  26838. * @param id defines the id to search for
  26839. * @return the mesh found or null if not found at all
  26840. */
  26841. Scene.prototype.getMeshByID = function (id) {
  26842. for (var index = 0; index < this.meshes.length; index++) {
  26843. if (this.meshes[index].id === id) {
  26844. return this.meshes[index];
  26845. }
  26846. }
  26847. return null;
  26848. };
  26849. /**
  26850. * Gets a list of meshes using their id
  26851. * @param id defines the id to search for
  26852. * @returns a list of meshes
  26853. */
  26854. Scene.prototype.getMeshesByID = function (id) {
  26855. return this.meshes.filter(function (m) {
  26856. return m.id === id;
  26857. });
  26858. };
  26859. /**
  26860. * Gets the first added transform node found of a given ID
  26861. * @param id defines the id to search for
  26862. * @return the found transform node or null if not found at all.
  26863. */
  26864. Scene.prototype.getTransformNodeByID = function (id) {
  26865. for (var index = 0; index < this.transformNodes.length; index++) {
  26866. if (this.transformNodes[index].id === id) {
  26867. return this.transformNodes[index];
  26868. }
  26869. }
  26870. return null;
  26871. };
  26872. /**
  26873. * Gets a list of transform nodes using their id
  26874. * @param id defines the id to search for
  26875. * @returns a list of transform nodes
  26876. */
  26877. Scene.prototype.getTransformNodesByID = function (id) {
  26878. return this.transformNodes.filter(function (m) {
  26879. return m.id === id;
  26880. });
  26881. };
  26882. /**
  26883. * Gets a mesh with its auto-generated unique id
  26884. * @param uniqueId defines the unique id to search for
  26885. * @return the found mesh or null if not found at all.
  26886. */
  26887. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26888. for (var index = 0; index < this.meshes.length; index++) {
  26889. if (this.meshes[index].uniqueId === uniqueId) {
  26890. return this.meshes[index];
  26891. }
  26892. }
  26893. return null;
  26894. };
  26895. /**
  26896. * Gets a the last added mesh using a given id
  26897. * @param id defines the id to search for
  26898. * @return the found mesh or null if not found at all.
  26899. */
  26900. Scene.prototype.getLastMeshByID = function (id) {
  26901. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26902. if (this.meshes[index].id === id) {
  26903. return this.meshes[index];
  26904. }
  26905. }
  26906. return null;
  26907. };
  26908. /**
  26909. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26910. * @param id defines the id to search for
  26911. * @return the found node or null if not found at all
  26912. */
  26913. Scene.prototype.getLastEntryByID = function (id) {
  26914. var index;
  26915. for (index = this.meshes.length - 1; index >= 0; index--) {
  26916. if (this.meshes[index].id === id) {
  26917. return this.meshes[index];
  26918. }
  26919. }
  26920. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26921. if (this.transformNodes[index].id === id) {
  26922. return this.transformNodes[index];
  26923. }
  26924. }
  26925. for (index = this.cameras.length - 1; index >= 0; index--) {
  26926. if (this.cameras[index].id === id) {
  26927. return this.cameras[index];
  26928. }
  26929. }
  26930. for (index = this.lights.length - 1; index >= 0; index--) {
  26931. if (this.lights[index].id === id) {
  26932. return this.lights[index];
  26933. }
  26934. }
  26935. return null;
  26936. };
  26937. /**
  26938. * Gets a node (Mesh, Camera, Light) using a given id
  26939. * @param id defines the id to search for
  26940. * @return the found node or null if not found at all
  26941. */
  26942. Scene.prototype.getNodeByID = function (id) {
  26943. var mesh = this.getMeshByID(id);
  26944. if (mesh) {
  26945. return mesh;
  26946. }
  26947. var light = this.getLightByID(id);
  26948. if (light) {
  26949. return light;
  26950. }
  26951. var camera = this.getCameraByID(id);
  26952. if (camera) {
  26953. return camera;
  26954. }
  26955. var bone = this.getBoneByID(id);
  26956. return bone;
  26957. };
  26958. /**
  26959. * Gets a node (Mesh, Camera, Light) using a given name
  26960. * @param name defines the name to search for
  26961. * @return the found node or null if not found at all.
  26962. */
  26963. Scene.prototype.getNodeByName = function (name) {
  26964. var mesh = this.getMeshByName(name);
  26965. if (mesh) {
  26966. return mesh;
  26967. }
  26968. var light = this.getLightByName(name);
  26969. if (light) {
  26970. return light;
  26971. }
  26972. var camera = this.getCameraByName(name);
  26973. if (camera) {
  26974. return camera;
  26975. }
  26976. var bone = this.getBoneByName(name);
  26977. return bone;
  26978. };
  26979. /**
  26980. * Gets a mesh using a given name
  26981. * @param name defines the name to search for
  26982. * @return the found mesh or null if not found at all.
  26983. */
  26984. Scene.prototype.getMeshByName = function (name) {
  26985. for (var index = 0; index < this.meshes.length; index++) {
  26986. if (this.meshes[index].name === name) {
  26987. return this.meshes[index];
  26988. }
  26989. }
  26990. return null;
  26991. };
  26992. /**
  26993. * Gets a transform node using a given name
  26994. * @param name defines the name to search for
  26995. * @return the found transform node or null if not found at all.
  26996. */
  26997. Scene.prototype.getTransformNodeByName = function (name) {
  26998. for (var index = 0; index < this.transformNodes.length; index++) {
  26999. if (this.transformNodes[index].name === name) {
  27000. return this.transformNodes[index];
  27001. }
  27002. }
  27003. return null;
  27004. };
  27005. /**
  27006. * Gets a sound using a given name
  27007. * @param name defines the name to search for
  27008. * @return the found sound or null if not found at all.
  27009. */
  27010. Scene.prototype.getSoundByName = function (name) {
  27011. var index;
  27012. if (BABYLON.AudioEngine) {
  27013. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27014. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27015. return this.mainSoundTrack.soundCollection[index];
  27016. }
  27017. }
  27018. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27019. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27020. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27021. return this.soundTracks[sdIndex].soundCollection[index];
  27022. }
  27023. }
  27024. }
  27025. }
  27026. return null;
  27027. };
  27028. /**
  27029. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27030. * @param id defines the id to search for
  27031. * @return the found skeleton or null if not found at all.
  27032. */
  27033. Scene.prototype.getLastSkeletonByID = function (id) {
  27034. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27035. if (this.skeletons[index].id === id) {
  27036. return this.skeletons[index];
  27037. }
  27038. }
  27039. return null;
  27040. };
  27041. /**
  27042. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27043. * @param id defines the id to search for
  27044. * @return the found skeleton or null if not found at all.
  27045. */
  27046. Scene.prototype.getSkeletonById = function (id) {
  27047. for (var index = 0; index < this.skeletons.length; index++) {
  27048. if (this.skeletons[index].id === id) {
  27049. return this.skeletons[index];
  27050. }
  27051. }
  27052. return null;
  27053. };
  27054. /**
  27055. * Gets a skeleton using a given name
  27056. * @param name defines the name to search for
  27057. * @return the found skeleton or null if not found at all.
  27058. */
  27059. Scene.prototype.getSkeletonByName = function (name) {
  27060. for (var index = 0; index < this.skeletons.length; index++) {
  27061. if (this.skeletons[index].name === name) {
  27062. return this.skeletons[index];
  27063. }
  27064. }
  27065. return null;
  27066. };
  27067. /**
  27068. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27069. * @param id defines the id to search for
  27070. * @return the found morph target manager or null if not found at all.
  27071. */
  27072. Scene.prototype.getMorphTargetManagerById = function (id) {
  27073. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27074. if (this.morphTargetManagers[index].uniqueId === id) {
  27075. return this.morphTargetManagers[index];
  27076. }
  27077. }
  27078. return null;
  27079. };
  27080. /**
  27081. * Gets a boolean indicating if the given mesh is active
  27082. * @param mesh defines the mesh to look for
  27083. * @returns true if the mesh is in the active list
  27084. */
  27085. Scene.prototype.isActiveMesh = function (mesh) {
  27086. return (this._activeMeshes.indexOf(mesh) !== -1);
  27087. };
  27088. /**
  27089. * Return a the first highlight layer of the scene with a given name.
  27090. * @param name The name of the highlight layer to look for.
  27091. * @return The highlight layer if found otherwise null.
  27092. */
  27093. Scene.prototype.getHighlightLayerByName = function (name) {
  27094. for (var index = 0; index < this.effectLayers.length; index++) {
  27095. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27096. return this.effectLayers[index];
  27097. }
  27098. }
  27099. return null;
  27100. };
  27101. /**
  27102. * Return a the first highlight layer of the scene with a given name.
  27103. * @param name The name of the highlight layer to look for.
  27104. * @return The highlight layer if found otherwise null.
  27105. */
  27106. Scene.prototype.getGlowLayerByName = function (name) {
  27107. for (var index = 0; index < this.effectLayers.length; index++) {
  27108. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27109. return this.effectLayers[index];
  27110. }
  27111. }
  27112. return null;
  27113. };
  27114. Object.defineProperty(Scene.prototype, "uid", {
  27115. /**
  27116. * Return a unique id as a string which can serve as an identifier for the scene
  27117. */
  27118. get: function () {
  27119. if (!this._uid) {
  27120. this._uid = BABYLON.Tools.RandomId();
  27121. }
  27122. return this._uid;
  27123. },
  27124. enumerable: true,
  27125. configurable: true
  27126. });
  27127. /**
  27128. * Add an externaly attached data from its key.
  27129. * This method call will fail and return false, if such key already exists.
  27130. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27131. * @param key the unique key that identifies the data
  27132. * @param data the data object to associate to the key for this Engine instance
  27133. * @return true if no such key were already present and the data was added successfully, false otherwise
  27134. */
  27135. Scene.prototype.addExternalData = function (key, data) {
  27136. if (!this._externalData) {
  27137. this._externalData = new BABYLON.StringDictionary();
  27138. }
  27139. return this._externalData.add(key, data);
  27140. };
  27141. /**
  27142. * Get an externaly attached data from its key
  27143. * @param key the unique key that identifies the data
  27144. * @return the associated data, if present (can be null), or undefined if not present
  27145. */
  27146. Scene.prototype.getExternalData = function (key) {
  27147. if (!this._externalData) {
  27148. return null;
  27149. }
  27150. return this._externalData.get(key);
  27151. };
  27152. /**
  27153. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27154. * @param key the unique key that identifies the data
  27155. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27156. * @return the associated data, can be null if the factory returned null.
  27157. */
  27158. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27159. if (!this._externalData) {
  27160. this._externalData = new BABYLON.StringDictionary();
  27161. }
  27162. return this._externalData.getOrAddWithFactory(key, factory);
  27163. };
  27164. /**
  27165. * Remove an externaly attached data from the Engine instance
  27166. * @param key the unique key that identifies the data
  27167. * @return true if the data was successfully removed, false if it doesn't exist
  27168. */
  27169. Scene.prototype.removeExternalData = function (key) {
  27170. return this._externalData.remove(key);
  27171. };
  27172. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27173. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27174. if (mesh.showSubMeshesBoundingBox) {
  27175. var boundingInfo = subMesh.getBoundingInfo();
  27176. if (boundingInfo !== null && boundingInfo !== undefined) {
  27177. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27178. }
  27179. }
  27180. var material = subMesh.getMaterial();
  27181. if (material !== null && material !== undefined) {
  27182. // Render targets
  27183. if (material.getRenderTargetTextures !== undefined) {
  27184. if (this._processedMaterials.indexOf(material) === -1) {
  27185. this._processedMaterials.push(material);
  27186. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27187. }
  27188. }
  27189. // Dispatch
  27190. this._activeIndices.addCount(subMesh.indexCount, false);
  27191. this._renderingManager.dispatch(subMesh, mesh, material);
  27192. }
  27193. }
  27194. };
  27195. /**
  27196. * Clear the processed materials smart array preventing retention point in material dispose.
  27197. */
  27198. Scene.prototype.freeProcessedMaterials = function () {
  27199. this._processedMaterials.dispose();
  27200. };
  27201. /**
  27202. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27203. */
  27204. Scene.prototype.freeActiveMeshes = function () {
  27205. this._activeMeshes.dispose();
  27206. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27207. this.activeCamera._activeMeshes.dispose();
  27208. }
  27209. if (this.activeCameras) {
  27210. for (var i = 0; i < this.activeCameras.length; i++) {
  27211. var activeCamera = this.activeCameras[i];
  27212. if (activeCamera && activeCamera._activeMeshes) {
  27213. activeCamera._activeMeshes.dispose();
  27214. }
  27215. }
  27216. }
  27217. };
  27218. /**
  27219. * Clear the info related to rendering groups preventing retention points during dispose.
  27220. */
  27221. Scene.prototype.freeRenderingGroups = function () {
  27222. if (this._renderingManager) {
  27223. this._renderingManager.freeRenderingGroups();
  27224. }
  27225. if (this.textures) {
  27226. for (var i = 0; i < this.textures.length; i++) {
  27227. var texture = this.textures[i];
  27228. if (texture && texture.renderList) {
  27229. texture.freeRenderingGroups();
  27230. }
  27231. }
  27232. }
  27233. };
  27234. /** @hidden */
  27235. Scene.prototype._isInIntermediateRendering = function () {
  27236. return this._intermediateRendering;
  27237. };
  27238. /**
  27239. * Defines the current active mesh candidate provider
  27240. * @param provider defines the provider to use
  27241. */
  27242. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27243. this._activeMeshCandidateProvider = provider;
  27244. };
  27245. /**
  27246. * Gets the current active mesh candidate provider
  27247. * @returns the current active mesh candidate provider
  27248. */
  27249. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27250. return this._activeMeshCandidateProvider;
  27251. };
  27252. /**
  27253. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27254. * @returns the current scene
  27255. */
  27256. Scene.prototype.freezeActiveMeshes = function () {
  27257. if (!this.activeCamera) {
  27258. return this;
  27259. }
  27260. if (!this._frustumPlanes) {
  27261. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27262. }
  27263. this._evaluateActiveMeshes();
  27264. this._activeMeshesFrozen = true;
  27265. return this;
  27266. };
  27267. /**
  27268. * Use this function to restart evaluating active meshes on every frame
  27269. * @returns the current scene
  27270. */
  27271. Scene.prototype.unfreezeActiveMeshes = function () {
  27272. this._activeMeshesFrozen = false;
  27273. return this;
  27274. };
  27275. Scene.prototype._evaluateActiveMeshes = function () {
  27276. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27277. return;
  27278. }
  27279. if (!this.activeCamera) {
  27280. return;
  27281. }
  27282. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27283. this.activeCamera._activeMeshes.reset();
  27284. this._activeMeshes.reset();
  27285. this._renderingManager.reset();
  27286. this._processedMaterials.reset();
  27287. this._activeParticleSystems.reset();
  27288. this._activeSkeletons.reset();
  27289. this._softwareSkinnedMeshes.reset();
  27290. if (this._boundingBoxRenderer) {
  27291. this._boundingBoxRenderer.reset();
  27292. }
  27293. // Meshes
  27294. var meshes;
  27295. var len;
  27296. var checkIsEnabled = true;
  27297. // Determine mesh candidates
  27298. if (this._activeMeshCandidateProvider !== undefined) {
  27299. // Use _activeMeshCandidateProvider
  27300. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27301. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27302. if (meshes !== undefined) {
  27303. len = meshes.length;
  27304. }
  27305. else {
  27306. len = 0;
  27307. }
  27308. }
  27309. else if (this._selectionOctree !== undefined) {
  27310. // Octree
  27311. var selection = this._selectionOctree.select(this._frustumPlanes);
  27312. meshes = selection.data;
  27313. len = selection.length;
  27314. }
  27315. else {
  27316. // Full scene traversal
  27317. len = this.meshes.length;
  27318. meshes = this.meshes;
  27319. }
  27320. // Check each mesh
  27321. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27322. mesh = meshes[meshIndex];
  27323. if (mesh.isBlocked) {
  27324. continue;
  27325. }
  27326. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27327. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27328. continue;
  27329. }
  27330. mesh.computeWorldMatrix();
  27331. // Intersections
  27332. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27333. this._meshesForIntersections.pushNoDuplicate(mesh);
  27334. }
  27335. // Switch to current LOD
  27336. meshLOD = mesh.getLOD(this.activeCamera);
  27337. if (meshLOD === undefined || meshLOD === null) {
  27338. continue;
  27339. }
  27340. mesh._preActivate();
  27341. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27342. this._activeMeshes.push(mesh);
  27343. this.activeCamera._activeMeshes.push(mesh);
  27344. mesh._activate(this._renderId);
  27345. if (meshLOD !== mesh) {
  27346. meshLOD._activate(this._renderId);
  27347. }
  27348. this._activeMesh(mesh, meshLOD);
  27349. }
  27350. }
  27351. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27352. // Particle systems
  27353. if (this.particlesEnabled) {
  27354. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27355. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27356. var particleSystem = this.particleSystems[particleIndex];
  27357. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27358. continue;
  27359. }
  27360. var emitter = particleSystem.emitter;
  27361. if (!emitter.position || emitter.isEnabled()) {
  27362. this._activeParticleSystems.push(particleSystem);
  27363. particleSystem.animate();
  27364. this._renderingManager.dispatchParticles(particleSystem);
  27365. }
  27366. }
  27367. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27368. }
  27369. };
  27370. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27371. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27372. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27373. mesh.skeleton.prepare();
  27374. }
  27375. if (!mesh.computeBonesUsingShaders) {
  27376. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27377. }
  27378. }
  27379. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27380. var boundingInfo = sourceMesh.getBoundingInfo();
  27381. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27382. }
  27383. if (mesh !== undefined && mesh !== null
  27384. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27385. // Submeshes Octrees
  27386. var len;
  27387. var subMeshes;
  27388. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27389. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27390. len = intersections.length;
  27391. subMeshes = intersections.data;
  27392. }
  27393. else {
  27394. subMeshes = mesh.subMeshes;
  27395. len = subMeshes.length;
  27396. }
  27397. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27398. subMesh = subMeshes[subIndex];
  27399. this._evaluateSubMesh(subMesh, mesh);
  27400. }
  27401. }
  27402. };
  27403. /**
  27404. * Update the transform matrix to update from the current active camera
  27405. * @param force defines a boolean used to force the update even if cache is up to date
  27406. */
  27407. Scene.prototype.updateTransformMatrix = function (force) {
  27408. if (!this.activeCamera) {
  27409. return;
  27410. }
  27411. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27412. };
  27413. /**
  27414. * 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)
  27415. * @param alternateCamera defines the camera to use
  27416. */
  27417. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27418. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27419. };
  27420. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27421. if (camera && camera._skipRendering) {
  27422. return;
  27423. }
  27424. var engine = this._engine;
  27425. this.activeCamera = camera;
  27426. if (!this.activeCamera)
  27427. throw new Error("Active camera not set");
  27428. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27429. // Viewport
  27430. engine.setViewport(this.activeCamera.viewport);
  27431. // Camera
  27432. this.resetCachedMaterial();
  27433. this._renderId++;
  27434. this.updateTransformMatrix();
  27435. if (camera._alternateCamera) {
  27436. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27437. this._alternateRendering = true;
  27438. }
  27439. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27440. // Meshes
  27441. this._evaluateActiveMeshes();
  27442. // Software skinning
  27443. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27444. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27445. mesh.applySkeleton(mesh.skeleton);
  27446. }
  27447. // Render targets
  27448. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27449. var needsRestoreFrameBuffer = false;
  27450. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27451. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27452. }
  27453. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27454. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27455. }
  27456. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27457. this._intermediateRendering = true;
  27458. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27459. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27460. var renderTarget = this._renderTargets.data[renderIndex];
  27461. if (renderTarget._shouldRender()) {
  27462. this._renderId++;
  27463. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27464. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27465. }
  27466. }
  27467. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27468. this._intermediateRendering = false;
  27469. this._renderId++;
  27470. needsRestoreFrameBuffer = true; // Restore back buffer
  27471. }
  27472. // Render EffecttLayer Texture
  27473. var stencilState = this._engine.getStencilBuffer();
  27474. var renderEffects = false;
  27475. var needStencil = false;
  27476. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27477. this._intermediateRendering = true;
  27478. for (var i = 0; i < this.effectLayers.length; i++) {
  27479. var effectLayer = this.effectLayers[i];
  27480. if (effectLayer.shouldRender() &&
  27481. (!effectLayer.camera ||
  27482. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27483. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27484. renderEffects = true;
  27485. needStencil = needStencil || effectLayer.needStencil();
  27486. var renderTarget = effectLayer._mainTexture;
  27487. if (renderTarget._shouldRender()) {
  27488. this._renderId++;
  27489. renderTarget.render(false, false);
  27490. needsRestoreFrameBuffer = true;
  27491. }
  27492. }
  27493. }
  27494. this._intermediateRendering = false;
  27495. this._renderId++;
  27496. }
  27497. if (needsRestoreFrameBuffer) {
  27498. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27499. }
  27500. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27501. // Prepare Frame
  27502. this.postProcessManager._prepareFrame();
  27503. // Backgrounds
  27504. var layerIndex;
  27505. var layer;
  27506. if (this.layers.length) {
  27507. engine.setDepthBuffer(false);
  27508. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27509. layer = this.layers[layerIndex];
  27510. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27511. layer.render();
  27512. }
  27513. }
  27514. engine.setDepthBuffer(true);
  27515. }
  27516. // Activate effect Layer stencil
  27517. if (needStencil) {
  27518. this._engine.setStencilBuffer(true);
  27519. }
  27520. // Render
  27521. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27522. this._renderingManager.render(null, null, true, true);
  27523. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27524. // Restore effect Layer stencil
  27525. if (needStencil) {
  27526. this._engine.setStencilBuffer(stencilState);
  27527. }
  27528. // Bounding boxes
  27529. if (this._boundingBoxRenderer) {
  27530. this._boundingBoxRenderer.render();
  27531. }
  27532. // Lens flares
  27533. if (this.lensFlaresEnabled) {
  27534. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27535. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27536. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27537. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27538. lensFlareSystem.render();
  27539. }
  27540. }
  27541. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27542. }
  27543. // Effect Layer
  27544. if (renderEffects) {
  27545. engine.setDepthBuffer(false);
  27546. for (var i = 0; i < this.effectLayers.length; i++) {
  27547. if (this.effectLayers[i].shouldRender()) {
  27548. this.effectLayers[i].render();
  27549. }
  27550. }
  27551. engine.setDepthBuffer(true);
  27552. }
  27553. // Foregrounds
  27554. if (this.layers.length) {
  27555. engine.setDepthBuffer(false);
  27556. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27557. layer = this.layers[layerIndex];
  27558. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27559. layer.render();
  27560. }
  27561. }
  27562. engine.setDepthBuffer(true);
  27563. }
  27564. // Finalize frame
  27565. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27566. // Reset some special arrays
  27567. this._renderTargets.reset();
  27568. this._alternateRendering = false;
  27569. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27570. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27571. };
  27572. Scene.prototype._processSubCameras = function (camera) {
  27573. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27574. this._renderForCamera(camera);
  27575. return;
  27576. }
  27577. // rig cameras
  27578. for (var index = 0; index < camera._rigCameras.length; index++) {
  27579. this._renderForCamera(camera._rigCameras[index], camera);
  27580. }
  27581. this.activeCamera = camera;
  27582. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27583. };
  27584. Scene.prototype._checkIntersections = function () {
  27585. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27586. var sourceMesh = this._meshesForIntersections.data[index];
  27587. if (!sourceMesh.actionManager) {
  27588. continue;
  27589. }
  27590. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27591. var action = sourceMesh.actionManager.actions[actionIndex];
  27592. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27593. var parameters = action.getTriggerParameter();
  27594. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27595. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27596. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27597. if (areIntersecting && currentIntersectionInProgress === -1) {
  27598. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27599. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27600. sourceMesh._intersectionsInProgress.push(otherMesh);
  27601. }
  27602. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27603. sourceMesh._intersectionsInProgress.push(otherMesh);
  27604. }
  27605. }
  27606. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27607. //They intersected, and now they don't.
  27608. //is this trigger an exit trigger? execute an event.
  27609. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27610. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27611. }
  27612. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27613. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27614. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27615. return otherMesh === parameterMesh;
  27616. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27617. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27618. }
  27619. }
  27620. }
  27621. }
  27622. }
  27623. };
  27624. /**
  27625. * Render the scene
  27626. */
  27627. Scene.prototype.render = function () {
  27628. if (this.isDisposed) {
  27629. return;
  27630. }
  27631. this._activeParticles.fetchNewFrame();
  27632. this._totalVertices.fetchNewFrame();
  27633. this._activeIndices.fetchNewFrame();
  27634. this._activeBones.fetchNewFrame();
  27635. this._meshesForIntersections.reset();
  27636. this.resetCachedMaterial();
  27637. this.onBeforeAnimationsObservable.notifyObservers(this);
  27638. // Actions
  27639. if (this.actionManager) {
  27640. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27641. }
  27642. //Simplification Queue
  27643. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27644. this.simplificationQueue.executeNext();
  27645. }
  27646. if (this._engine.isDeterministicLockStep()) {
  27647. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27648. var defaultFPS = (60.0 / 1000.0);
  27649. var defaultFrameTime = 1000 / 60; // frame time in MS
  27650. if (this._physicsEngine) {
  27651. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27652. }
  27653. var stepsTaken = 0;
  27654. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27655. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27656. internalSteps = Math.min(internalSteps, maxSubSteps);
  27657. do {
  27658. this.onBeforeStepObservable.notifyObservers(this);
  27659. // Animations
  27660. this._animationRatio = defaultFrameTime * defaultFPS;
  27661. this._animate();
  27662. this.onAfterAnimationsObservable.notifyObservers(this);
  27663. // Physics
  27664. if (this._physicsEngine) {
  27665. this.onBeforePhysicsObservable.notifyObservers(this);
  27666. this._physicsEngine._step(defaultFrameTime / 1000);
  27667. this.onAfterPhysicsObservable.notifyObservers(this);
  27668. }
  27669. this.onAfterStepObservable.notifyObservers(this);
  27670. this._currentStepId++;
  27671. stepsTaken++;
  27672. deltaTime -= defaultFrameTime;
  27673. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27674. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27675. }
  27676. else {
  27677. // Animations
  27678. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27679. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27680. this._animate();
  27681. this.onAfterAnimationsObservable.notifyObservers(this);
  27682. // Physics
  27683. if (this._physicsEngine) {
  27684. this.onBeforePhysicsObservable.notifyObservers(this);
  27685. this._physicsEngine._step(deltaTime / 1000.0);
  27686. this.onAfterPhysicsObservable.notifyObservers(this);
  27687. }
  27688. }
  27689. // update gamepad manager
  27690. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27691. this._gamepadManager._checkGamepadsStatus();
  27692. }
  27693. // Update Cameras
  27694. if (this.activeCameras.length > 0) {
  27695. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27696. var camera = this.activeCameras[cameraIndex];
  27697. camera.update();
  27698. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27699. // rig cameras
  27700. for (var index = 0; index < camera._rigCameras.length; index++) {
  27701. camera._rigCameras[index].update();
  27702. }
  27703. }
  27704. }
  27705. }
  27706. else if (this.activeCamera) {
  27707. this.activeCamera.update();
  27708. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27709. // rig cameras
  27710. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27711. this.activeCamera._rigCameras[index].update();
  27712. }
  27713. }
  27714. }
  27715. // Before render
  27716. this.onBeforeRenderObservable.notifyObservers(this);
  27717. // Customs render targets
  27718. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27719. var engine = this.getEngine();
  27720. var currentActiveCamera = this.activeCamera;
  27721. if (this.renderTargetsEnabled) {
  27722. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27723. this._intermediateRendering = true;
  27724. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27725. var renderTarget = this.customRenderTargets[customIndex];
  27726. if (renderTarget._shouldRender()) {
  27727. this._renderId++;
  27728. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27729. if (!this.activeCamera)
  27730. throw new Error("Active camera not set");
  27731. // Viewport
  27732. engine.setViewport(this.activeCamera.viewport);
  27733. // Camera
  27734. this.updateTransformMatrix();
  27735. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27736. }
  27737. }
  27738. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27739. this._intermediateRendering = false;
  27740. this._renderId++;
  27741. }
  27742. // Restore back buffer
  27743. if (this.customRenderTargets.length > 0) {
  27744. engine.restoreDefaultFramebuffer();
  27745. }
  27746. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27747. this.activeCamera = currentActiveCamera;
  27748. // Procedural textures
  27749. if (this.proceduralTexturesEnabled) {
  27750. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27751. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27752. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27753. if (proceduralTexture._shouldRender()) {
  27754. proceduralTexture.render();
  27755. }
  27756. }
  27757. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27758. }
  27759. // Clear
  27760. if (this.autoClearDepthAndStencil || this.autoClear) {
  27761. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27762. }
  27763. // Shadows
  27764. if (this.shadowsEnabled) {
  27765. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27766. var light = this.lights[lightIndex];
  27767. var shadowGenerator = light.getShadowGenerator();
  27768. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27769. var shadowMap = (shadowGenerator.getShadowMap());
  27770. if (this.textures.indexOf(shadowMap) !== -1) {
  27771. this._renderTargets.push(shadowMap);
  27772. }
  27773. }
  27774. }
  27775. }
  27776. // Depth renderer
  27777. for (var key in this._depthRenderer) {
  27778. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27779. }
  27780. // Geometry renderer
  27781. if (this._geometryBufferRenderer) {
  27782. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27783. }
  27784. // RenderPipeline
  27785. if (this._postProcessRenderPipelineManager) {
  27786. this._postProcessRenderPipelineManager.update();
  27787. }
  27788. // Multi-cameras?
  27789. if (this.activeCameras.length > 0) {
  27790. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27791. if (cameraIndex > 0) {
  27792. this._engine.clear(null, false, true, true);
  27793. }
  27794. this._processSubCameras(this.activeCameras[cameraIndex]);
  27795. }
  27796. }
  27797. else {
  27798. if (!this.activeCamera) {
  27799. throw new Error("No camera defined");
  27800. }
  27801. this._processSubCameras(this.activeCamera);
  27802. }
  27803. // Intersection checks
  27804. this._checkIntersections();
  27805. // Update the audio listener attached to the camera
  27806. if (BABYLON.AudioEngine) {
  27807. this._updateAudioParameters();
  27808. }
  27809. // After render
  27810. if (this.afterRender) {
  27811. this.afterRender();
  27812. }
  27813. this.onAfterRenderObservable.notifyObservers(this);
  27814. // Cleaning
  27815. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27816. var data = this._toBeDisposed.data[index];
  27817. if (data) {
  27818. data.dispose();
  27819. }
  27820. this._toBeDisposed[index] = null;
  27821. }
  27822. this._toBeDisposed.reset();
  27823. if (this.dumpNextRenderTargets) {
  27824. this.dumpNextRenderTargets = false;
  27825. }
  27826. this._activeBones.addCount(0, true);
  27827. this._activeIndices.addCount(0, true);
  27828. this._activeParticles.addCount(0, true);
  27829. };
  27830. Scene.prototype._updateAudioParameters = function () {
  27831. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27832. return;
  27833. }
  27834. var listeningCamera;
  27835. var audioEngine = BABYLON.Engine.audioEngine;
  27836. if (this.activeCameras.length > 0) {
  27837. listeningCamera = this.activeCameras[0];
  27838. }
  27839. else {
  27840. listeningCamera = this.activeCamera;
  27841. }
  27842. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27843. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27844. // for VR cameras
  27845. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27846. listeningCamera = listeningCamera.rigCameras[0];
  27847. }
  27848. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27849. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27850. cameraDirection.normalize();
  27851. // To avoid some errors on GearVR
  27852. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27853. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27854. }
  27855. var i;
  27856. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27857. var sound = this.mainSoundTrack.soundCollection[i];
  27858. if (sound.useCustomAttenuation) {
  27859. sound.updateDistanceFromListener();
  27860. }
  27861. }
  27862. for (i = 0; i < this.soundTracks.length; i++) {
  27863. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27864. sound = this.soundTracks[i].soundCollection[j];
  27865. if (sound.useCustomAttenuation) {
  27866. sound.updateDistanceFromListener();
  27867. }
  27868. }
  27869. }
  27870. }
  27871. };
  27872. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27873. // Audio
  27874. /**
  27875. * Gets or sets if audio support is enabled
  27876. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27877. */
  27878. get: function () {
  27879. return this._audioEnabled;
  27880. },
  27881. set: function (value) {
  27882. this._audioEnabled = value;
  27883. if (BABYLON.AudioEngine) {
  27884. if (this._audioEnabled) {
  27885. this._enableAudio();
  27886. }
  27887. else {
  27888. this._disableAudio();
  27889. }
  27890. }
  27891. },
  27892. enumerable: true,
  27893. configurable: true
  27894. });
  27895. Scene.prototype._disableAudio = function () {
  27896. var i;
  27897. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27898. this.mainSoundTrack.soundCollection[i].pause();
  27899. }
  27900. for (i = 0; i < this.soundTracks.length; i++) {
  27901. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27902. this.soundTracks[i].soundCollection[j].pause();
  27903. }
  27904. }
  27905. };
  27906. Scene.prototype._enableAudio = function () {
  27907. var i;
  27908. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27909. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27910. this.mainSoundTrack.soundCollection[i].play();
  27911. }
  27912. }
  27913. for (i = 0; i < this.soundTracks.length; i++) {
  27914. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27915. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27916. this.soundTracks[i].soundCollection[j].play();
  27917. }
  27918. }
  27919. }
  27920. };
  27921. Object.defineProperty(Scene.prototype, "headphone", {
  27922. /**
  27923. * Gets or sets if audio will be output to headphones
  27924. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27925. */
  27926. get: function () {
  27927. return this._headphone;
  27928. },
  27929. set: function (value) {
  27930. this._headphone = value;
  27931. if (BABYLON.AudioEngine) {
  27932. if (this._headphone) {
  27933. this._switchAudioModeForHeadphones();
  27934. }
  27935. else {
  27936. this._switchAudioModeForNormalSpeakers();
  27937. }
  27938. }
  27939. },
  27940. enumerable: true,
  27941. configurable: true
  27942. });
  27943. Scene.prototype._switchAudioModeForHeadphones = function () {
  27944. this.mainSoundTrack.switchPanningModelToHRTF();
  27945. for (var i = 0; i < this.soundTracks.length; i++) {
  27946. this.soundTracks[i].switchPanningModelToHRTF();
  27947. }
  27948. };
  27949. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27950. this.mainSoundTrack.switchPanningModelToEqualPower();
  27951. for (var i = 0; i < this.soundTracks.length; i++) {
  27952. this.soundTracks[i].switchPanningModelToEqualPower();
  27953. }
  27954. };
  27955. /**
  27956. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27957. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27958. * @returns the created depth renderer
  27959. */
  27960. Scene.prototype.enableDepthRenderer = function (camera) {
  27961. camera = camera || this.activeCamera;
  27962. if (!camera) {
  27963. throw "No camera available to enable depth renderer";
  27964. }
  27965. if (!this._depthRenderer[camera.id]) {
  27966. var textureType = 0;
  27967. if (this._engine.getCaps().textureHalfFloatRender) {
  27968. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27969. }
  27970. else if (this._engine.getCaps().textureFloatRender) {
  27971. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27972. }
  27973. else {
  27974. throw "Depth renderer does not support int texture type";
  27975. }
  27976. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27977. }
  27978. return this._depthRenderer[camera.id];
  27979. };
  27980. /**
  27981. * Disables a depth renderer for a given camera
  27982. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27983. */
  27984. Scene.prototype.disableDepthRenderer = function (camera) {
  27985. camera = camera || this.activeCamera;
  27986. if (!camera || !this._depthRenderer[camera.id]) {
  27987. return;
  27988. }
  27989. this._depthRenderer[camera.id].dispose();
  27990. delete this._depthRenderer[camera.id];
  27991. };
  27992. /**
  27993. * Enables a GeometryBufferRender and associates it with the scene
  27994. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27995. * @returns the GeometryBufferRenderer
  27996. */
  27997. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27998. if (ratio === void 0) { ratio = 1; }
  27999. if (this._geometryBufferRenderer) {
  28000. return this._geometryBufferRenderer;
  28001. }
  28002. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28003. if (!this._geometryBufferRenderer.isSupported) {
  28004. this._geometryBufferRenderer = null;
  28005. }
  28006. return this._geometryBufferRenderer;
  28007. };
  28008. /**
  28009. * Disables the GeometryBufferRender associated with the scene
  28010. */
  28011. Scene.prototype.disableGeometryBufferRenderer = function () {
  28012. if (!this._geometryBufferRenderer) {
  28013. return;
  28014. }
  28015. this._geometryBufferRenderer.dispose();
  28016. this._geometryBufferRenderer = null;
  28017. };
  28018. /**
  28019. * Freeze all materials
  28020. * A frozen material will not be updatable but should be faster to render
  28021. */
  28022. Scene.prototype.freezeMaterials = function () {
  28023. for (var i = 0; i < this.materials.length; i++) {
  28024. this.materials[i].freeze();
  28025. }
  28026. };
  28027. /**
  28028. * Unfreeze all materials
  28029. * A frozen material will not be updatable but should be faster to render
  28030. */
  28031. Scene.prototype.unfreezeMaterials = function () {
  28032. for (var i = 0; i < this.materials.length; i++) {
  28033. this.materials[i].unfreeze();
  28034. }
  28035. };
  28036. /**
  28037. * Releases all held ressources
  28038. */
  28039. Scene.prototype.dispose = function () {
  28040. this.beforeRender = null;
  28041. this.afterRender = null;
  28042. this.skeletons = [];
  28043. this.morphTargetManagers = [];
  28044. this.importedMeshesFiles = new Array();
  28045. this.stopAllAnimations();
  28046. this.resetCachedMaterial();
  28047. for (var key in this._depthRenderer) {
  28048. this._depthRenderer[key].dispose();
  28049. }
  28050. if (this._gamepadManager) {
  28051. this._gamepadManager.dispose();
  28052. this._gamepadManager = null;
  28053. }
  28054. // Smart arrays
  28055. if (this.activeCamera) {
  28056. this.activeCamera._activeMeshes.dispose();
  28057. this.activeCamera = null;
  28058. }
  28059. this._activeMeshes.dispose();
  28060. this._renderingManager.dispose();
  28061. this._processedMaterials.dispose();
  28062. this._activeParticleSystems.dispose();
  28063. this._activeSkeletons.dispose();
  28064. this._softwareSkinnedMeshes.dispose();
  28065. this._renderTargets.dispose();
  28066. this._registeredForLateAnimationBindings.dispose();
  28067. if (this._boundingBoxRenderer) {
  28068. this._boundingBoxRenderer.dispose();
  28069. }
  28070. this._meshesForIntersections.dispose();
  28071. this._toBeDisposed.dispose();
  28072. // Abort active requests
  28073. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28074. var request = _a[_i];
  28075. request.abort();
  28076. }
  28077. // Debug layer
  28078. if (this._debugLayer) {
  28079. this._debugLayer.hide();
  28080. }
  28081. // Events
  28082. this.onDisposeObservable.notifyObservers(this);
  28083. this.onDisposeObservable.clear();
  28084. this.onBeforeRenderObservable.clear();
  28085. this.onAfterRenderObservable.clear();
  28086. this.onBeforeRenderTargetsRenderObservable.clear();
  28087. this.onAfterRenderTargetsRenderObservable.clear();
  28088. this.onAfterStepObservable.clear();
  28089. this.onBeforeStepObservable.clear();
  28090. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28091. this.onAfterActiveMeshesEvaluationObservable.clear();
  28092. this.onBeforeParticlesRenderingObservable.clear();
  28093. this.onAfterParticlesRenderingObservable.clear();
  28094. this.onBeforeSpritesRenderingObservable.clear();
  28095. this.onAfterSpritesRenderingObservable.clear();
  28096. this.onBeforeDrawPhaseObservable.clear();
  28097. this.onAfterDrawPhaseObservable.clear();
  28098. this.onBeforePhysicsObservable.clear();
  28099. this.onAfterPhysicsObservable.clear();
  28100. this.onBeforeAnimationsObservable.clear();
  28101. this.onAfterAnimationsObservable.clear();
  28102. this.onDataLoadedObservable.clear();
  28103. this.detachControl();
  28104. // Release sounds & sounds tracks
  28105. if (BABYLON.AudioEngine) {
  28106. this.disposeSounds();
  28107. }
  28108. // VR Helper
  28109. if (this.VRHelper) {
  28110. this.VRHelper.dispose();
  28111. }
  28112. // Detach cameras
  28113. var canvas = this._engine.getRenderingCanvas();
  28114. if (canvas) {
  28115. var index;
  28116. for (index = 0; index < this.cameras.length; index++) {
  28117. this.cameras[index].detachControl(canvas);
  28118. }
  28119. }
  28120. // Release animation groups
  28121. while (this.animationGroups.length) {
  28122. this.animationGroups[0].dispose();
  28123. }
  28124. // Release lights
  28125. while (this.lights.length) {
  28126. this.lights[0].dispose();
  28127. }
  28128. // Release meshes
  28129. while (this.meshes.length) {
  28130. this.meshes[0].dispose(true);
  28131. }
  28132. while (this.transformNodes.length) {
  28133. this.removeTransformNode(this.transformNodes[0]);
  28134. }
  28135. // Release cameras
  28136. while (this.cameras.length) {
  28137. this.cameras[0].dispose();
  28138. }
  28139. // Release materials
  28140. if (this.defaultMaterial) {
  28141. this.defaultMaterial.dispose();
  28142. }
  28143. while (this.multiMaterials.length) {
  28144. this.multiMaterials[0].dispose();
  28145. }
  28146. while (this.materials.length) {
  28147. this.materials[0].dispose();
  28148. }
  28149. // Release particles
  28150. while (this.particleSystems.length) {
  28151. this.particleSystems[0].dispose();
  28152. }
  28153. // Release sprites
  28154. while (this.spriteManagers.length) {
  28155. this.spriteManagers[0].dispose();
  28156. }
  28157. // Release postProcesses
  28158. while (this.postProcesses.length) {
  28159. this.postProcesses[0].dispose();
  28160. }
  28161. // Release layers
  28162. while (this.layers.length) {
  28163. this.layers[0].dispose();
  28164. }
  28165. while (this.effectLayers.length) {
  28166. this.effectLayers[0].dispose();
  28167. }
  28168. // Release textures
  28169. while (this.textures.length) {
  28170. this.textures[0].dispose();
  28171. }
  28172. // Release UBO
  28173. this._sceneUbo.dispose();
  28174. if (this._alternateSceneUbo) {
  28175. this._alternateSceneUbo.dispose();
  28176. }
  28177. // Post-processes
  28178. this.postProcessManager.dispose();
  28179. if (this._postProcessRenderPipelineManager) {
  28180. this._postProcessRenderPipelineManager.dispose();
  28181. }
  28182. // Physics
  28183. if (this._physicsEngine) {
  28184. this.disablePhysicsEngine();
  28185. }
  28186. // Remove from engine
  28187. index = this._engine.scenes.indexOf(this);
  28188. if (index > -1) {
  28189. this._engine.scenes.splice(index, 1);
  28190. }
  28191. this._engine.wipeCaches(true);
  28192. this._isDisposed = true;
  28193. };
  28194. Object.defineProperty(Scene.prototype, "isDisposed", {
  28195. /**
  28196. * Gets if the scene is already disposed
  28197. */
  28198. get: function () {
  28199. return this._isDisposed;
  28200. },
  28201. enumerable: true,
  28202. configurable: true
  28203. });
  28204. /**
  28205. * Releases sounds & soundtracks
  28206. */
  28207. Scene.prototype.disposeSounds = function () {
  28208. if (!this._mainSoundTrack) {
  28209. return;
  28210. }
  28211. this.mainSoundTrack.dispose();
  28212. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28213. this.soundTracks[scIndex].dispose();
  28214. }
  28215. };
  28216. /**
  28217. * Call this function to reduce memory footprint of the scene.
  28218. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28219. */
  28220. Scene.prototype.clearCachedVertexData = function () {
  28221. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28222. var mesh = this.meshes[meshIndex];
  28223. var geometry = mesh.geometry;
  28224. if (geometry) {
  28225. geometry._indices = [];
  28226. for (var vbName in geometry._vertexBuffers) {
  28227. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28228. continue;
  28229. }
  28230. geometry._vertexBuffers[vbName]._buffer._data = null;
  28231. }
  28232. }
  28233. }
  28234. };
  28235. /**
  28236. * This function will remove the local cached buffer data from texture.
  28237. * It will save memory but will prevent the texture from being rebuilt
  28238. */
  28239. Scene.prototype.cleanCachedTextureBuffer = function () {
  28240. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28241. var baseTexture = _a[_i];
  28242. var buffer = baseTexture._buffer;
  28243. if (buffer) {
  28244. baseTexture._buffer = null;
  28245. }
  28246. }
  28247. };
  28248. // Octrees
  28249. /**
  28250. * Get the world extend vectors with an optional filter
  28251. *
  28252. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28253. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28254. */
  28255. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28256. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28257. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28258. filterPredicate = filterPredicate || (function () { return true; });
  28259. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28260. mesh.computeWorldMatrix(true);
  28261. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28262. return;
  28263. }
  28264. var boundingInfo = mesh.getBoundingInfo();
  28265. var minBox = boundingInfo.boundingBox.minimumWorld;
  28266. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28267. BABYLON.Tools.CheckExtends(minBox, min, max);
  28268. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28269. });
  28270. return {
  28271. min: min,
  28272. max: max
  28273. };
  28274. };
  28275. /**
  28276. * Creates or updates the octree used to boost selection (picking)
  28277. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28278. * @param maxCapacity defines the maximum capacity per leaf
  28279. * @param maxDepth defines the maximum depth of the octree
  28280. * @returns an octree of AbstractMesh
  28281. */
  28282. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28283. if (maxCapacity === void 0) { maxCapacity = 64; }
  28284. if (maxDepth === void 0) { maxDepth = 2; }
  28285. if (!this._selectionOctree) {
  28286. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28287. }
  28288. var worldExtends = this.getWorldExtends();
  28289. // Update octree
  28290. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28291. return this._selectionOctree;
  28292. };
  28293. // Picking
  28294. /**
  28295. * Creates a ray that can be used to pick in the scene
  28296. * @param x defines the x coordinate of the origin (on-screen)
  28297. * @param y defines the y coordinate of the origin (on-screen)
  28298. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28299. * @param camera defines the camera to use for the picking
  28300. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28301. * @returns a Ray
  28302. */
  28303. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28304. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28305. var result = BABYLON.Ray.Zero();
  28306. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28307. return result;
  28308. };
  28309. /**
  28310. * Creates a ray that can be used to pick in the scene
  28311. * @param x defines the x coordinate of the origin (on-screen)
  28312. * @param y defines the y coordinate of the origin (on-screen)
  28313. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28314. * @param result defines the ray where to store the picking ray
  28315. * @param camera defines the camera to use for the picking
  28316. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28317. * @returns the current scene
  28318. */
  28319. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28320. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28321. var engine = this._engine;
  28322. if (!camera) {
  28323. if (!this.activeCamera)
  28324. throw new Error("Active camera not set");
  28325. camera = this.activeCamera;
  28326. }
  28327. var cameraViewport = camera.viewport;
  28328. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28329. // Moving coordinates to local viewport world
  28330. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28331. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28332. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28333. return this;
  28334. };
  28335. /**
  28336. * Creates a ray that can be used to pick in the scene
  28337. * @param x defines the x coordinate of the origin (on-screen)
  28338. * @param y defines the y coordinate of the origin (on-screen)
  28339. * @param camera defines the camera to use for the picking
  28340. * @returns a Ray
  28341. */
  28342. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28343. var result = BABYLON.Ray.Zero();
  28344. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28345. return result;
  28346. };
  28347. /**
  28348. * Creates a ray that can be used to pick in the scene
  28349. * @param x defines the x coordinate of the origin (on-screen)
  28350. * @param y defines the y coordinate of the origin (on-screen)
  28351. * @param result defines the ray where to store the picking ray
  28352. * @param camera defines the camera to use for the picking
  28353. * @returns the current scene
  28354. */
  28355. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28356. if (!BABYLON.PickingInfo) {
  28357. return this;
  28358. }
  28359. var engine = this._engine;
  28360. if (!camera) {
  28361. if (!this.activeCamera)
  28362. throw new Error("Active camera not set");
  28363. camera = this.activeCamera;
  28364. }
  28365. var cameraViewport = camera.viewport;
  28366. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28367. var identity = BABYLON.Matrix.Identity();
  28368. // Moving coordinates to local viewport world
  28369. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28370. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28371. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28372. return this;
  28373. };
  28374. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28375. if (!BABYLON.PickingInfo) {
  28376. return null;
  28377. }
  28378. var pickingInfo = null;
  28379. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28380. var mesh = this.meshes[meshIndex];
  28381. if (predicate) {
  28382. if (!predicate(mesh)) {
  28383. continue;
  28384. }
  28385. }
  28386. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28387. continue;
  28388. }
  28389. var world = mesh.getWorldMatrix();
  28390. var ray = rayFunction(world);
  28391. var result = mesh.intersects(ray, fastCheck);
  28392. if (!result || !result.hit)
  28393. continue;
  28394. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28395. continue;
  28396. pickingInfo = result;
  28397. if (fastCheck) {
  28398. break;
  28399. }
  28400. }
  28401. return pickingInfo || new BABYLON.PickingInfo();
  28402. };
  28403. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28404. if (!BABYLON.PickingInfo) {
  28405. return null;
  28406. }
  28407. var pickingInfos = new Array();
  28408. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28409. var mesh = this.meshes[meshIndex];
  28410. if (predicate) {
  28411. if (!predicate(mesh)) {
  28412. continue;
  28413. }
  28414. }
  28415. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28416. continue;
  28417. }
  28418. var world = mesh.getWorldMatrix();
  28419. var ray = rayFunction(world);
  28420. var result = mesh.intersects(ray, false);
  28421. if (!result || !result.hit)
  28422. continue;
  28423. pickingInfos.push(result);
  28424. }
  28425. return pickingInfos;
  28426. };
  28427. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28428. if (!BABYLON.PickingInfo) {
  28429. return null;
  28430. }
  28431. var pickingInfo = null;
  28432. if (!camera) {
  28433. if (!this.activeCamera) {
  28434. return null;
  28435. }
  28436. camera = this.activeCamera;
  28437. }
  28438. if (this.spriteManagers.length > 0) {
  28439. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28440. var spriteManager = this.spriteManagers[spriteIndex];
  28441. if (!spriteManager.isPickable) {
  28442. continue;
  28443. }
  28444. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28445. if (!result || !result.hit)
  28446. continue;
  28447. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28448. continue;
  28449. pickingInfo = result;
  28450. if (fastCheck) {
  28451. break;
  28452. }
  28453. }
  28454. }
  28455. return pickingInfo || new BABYLON.PickingInfo();
  28456. };
  28457. /** Launch a ray to try to pick a mesh in the scene
  28458. * @param x position on screen
  28459. * @param y position on screen
  28460. * @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
  28461. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28462. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28463. * @returns a PickingInfo
  28464. */
  28465. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28466. var _this = this;
  28467. if (!BABYLON.PickingInfo) {
  28468. return null;
  28469. }
  28470. return this._internalPick(function (world) {
  28471. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28472. return _this._tempPickingRay;
  28473. }, predicate, fastCheck);
  28474. };
  28475. /** Launch a ray to try to pick a sprite in the scene
  28476. * @param x position on screen
  28477. * @param y position on screen
  28478. * @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
  28479. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28480. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28481. * @returns a PickingInfo
  28482. */
  28483. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28484. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28485. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28486. };
  28487. /** Use the given ray to pick a mesh in the scene
  28488. * @param ray The ray to use to pick meshes
  28489. * @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
  28490. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28491. * @returns a PickingInfo
  28492. */
  28493. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28494. var _this = this;
  28495. return this._internalPick(function (world) {
  28496. if (!_this._pickWithRayInverseMatrix) {
  28497. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28498. }
  28499. world.invertToRef(_this._pickWithRayInverseMatrix);
  28500. if (!_this._cachedRayForTransform) {
  28501. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28502. }
  28503. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28504. return _this._cachedRayForTransform;
  28505. }, predicate, fastCheck);
  28506. };
  28507. /**
  28508. * Launch a ray to try to pick a mesh in the scene
  28509. * @param x X position on screen
  28510. * @param y Y position on screen
  28511. * @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
  28512. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28513. * @returns an array of PickingInfo
  28514. */
  28515. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28516. var _this = this;
  28517. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28518. };
  28519. /**
  28520. * Launch a ray to try to pick a mesh in the scene
  28521. * @param ray Ray to use
  28522. * @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
  28523. * @returns an array of PickingInfo
  28524. */
  28525. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28526. var _this = this;
  28527. return this._internalMultiPick(function (world) {
  28528. if (!_this._pickWithRayInverseMatrix) {
  28529. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28530. }
  28531. world.invertToRef(_this._pickWithRayInverseMatrix);
  28532. if (!_this._cachedRayForTransform) {
  28533. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28534. }
  28535. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28536. return _this._cachedRayForTransform;
  28537. }, predicate);
  28538. };
  28539. /**
  28540. * Force the value of meshUnderPointer
  28541. * @param mesh defines the mesh to use
  28542. */
  28543. Scene.prototype.setPointerOverMesh = function (mesh) {
  28544. if (this._pointerOverMesh === mesh) {
  28545. return;
  28546. }
  28547. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28548. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28549. }
  28550. this._pointerOverMesh = mesh;
  28551. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28552. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28553. }
  28554. };
  28555. /**
  28556. * Gets the mesh under the pointer
  28557. * @returns a Mesh or null if no mesh is under the pointer
  28558. */
  28559. Scene.prototype.getPointerOverMesh = function () {
  28560. return this._pointerOverMesh;
  28561. };
  28562. /**
  28563. * Force the sprite under the pointer
  28564. * @param sprite defines the sprite to use
  28565. */
  28566. Scene.prototype.setPointerOverSprite = function (sprite) {
  28567. if (this._pointerOverSprite === sprite) {
  28568. return;
  28569. }
  28570. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28571. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28572. }
  28573. this._pointerOverSprite = sprite;
  28574. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28575. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28576. }
  28577. };
  28578. /**
  28579. * Gets the sprite under the pointer
  28580. * @returns a Sprite or null if no sprite is under the pointer
  28581. */
  28582. Scene.prototype.getPointerOverSprite = function () {
  28583. return this._pointerOverSprite;
  28584. };
  28585. // Physics
  28586. /**
  28587. * Gets the current physics engine
  28588. * @returns a PhysicsEngine or null if none attached
  28589. */
  28590. Scene.prototype.getPhysicsEngine = function () {
  28591. return this._physicsEngine;
  28592. };
  28593. /**
  28594. * Enables physics to the current scene
  28595. * @param gravity defines the scene's gravity for the physics engine
  28596. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28597. * @return a boolean indicating if the physics engine was initialized
  28598. */
  28599. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28600. if (gravity === void 0) { gravity = null; }
  28601. if (this._physicsEngine) {
  28602. return true;
  28603. }
  28604. try {
  28605. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28606. return true;
  28607. }
  28608. catch (e) {
  28609. BABYLON.Tools.Error(e.message);
  28610. return false;
  28611. }
  28612. };
  28613. /**
  28614. * Disables and disposes the physics engine associated with the scene
  28615. */
  28616. Scene.prototype.disablePhysicsEngine = function () {
  28617. if (!this._physicsEngine) {
  28618. return;
  28619. }
  28620. this._physicsEngine.dispose();
  28621. this._physicsEngine = null;
  28622. };
  28623. /**
  28624. * Gets a boolean indicating if there is an active physics engine
  28625. * @returns a boolean indicating if there is an active physics engine
  28626. */
  28627. Scene.prototype.isPhysicsEnabled = function () {
  28628. return this._physicsEngine !== undefined;
  28629. };
  28630. /**
  28631. * Deletes a physics compound impostor
  28632. * @param compound defines the compound to delete
  28633. */
  28634. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28635. var mesh = compound.parts[0].mesh;
  28636. if (mesh.physicsImpostor) {
  28637. mesh.physicsImpostor.dispose( /*true*/);
  28638. mesh.physicsImpostor = null;
  28639. }
  28640. };
  28641. // Misc.
  28642. /** @hidden */
  28643. Scene.prototype._rebuildGeometries = function () {
  28644. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28645. var geometry = _a[_i];
  28646. geometry._rebuild();
  28647. }
  28648. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28649. var mesh = _c[_b];
  28650. mesh._rebuild();
  28651. }
  28652. if (this.postProcessManager) {
  28653. this.postProcessManager._rebuild();
  28654. }
  28655. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28656. var layer = _e[_d];
  28657. layer._rebuild();
  28658. }
  28659. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28660. var effectLayer = _g[_f];
  28661. effectLayer._rebuild();
  28662. }
  28663. if (this._boundingBoxRenderer) {
  28664. this._boundingBoxRenderer._rebuild();
  28665. }
  28666. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28667. var system = _j[_h];
  28668. system.rebuild();
  28669. }
  28670. if (this._postProcessRenderPipelineManager) {
  28671. this._postProcessRenderPipelineManager._rebuild();
  28672. }
  28673. };
  28674. /** @hidden */
  28675. Scene.prototype._rebuildTextures = function () {
  28676. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28677. var texture = _a[_i];
  28678. texture._rebuild();
  28679. }
  28680. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28681. };
  28682. /**
  28683. * Creates a default light for the scene.
  28684. * @param replace Whether to replace the existing lights in the scene.
  28685. */
  28686. Scene.prototype.createDefaultLight = function (replace) {
  28687. if (replace === void 0) { replace = false; }
  28688. // Dispose existing light in replace mode.
  28689. if (replace) {
  28690. if (this.lights) {
  28691. for (var i = 0; i < this.lights.length; i++) {
  28692. this.lights[i].dispose();
  28693. }
  28694. }
  28695. }
  28696. // Light
  28697. if (this.lights.length === 0) {
  28698. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28699. }
  28700. };
  28701. /**
  28702. * Creates a default camera for the scene.
  28703. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28704. * @param replace Whether to replace the existing active camera in the scene.
  28705. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28706. */
  28707. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28708. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28709. if (replace === void 0) { replace = false; }
  28710. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28711. // Dispose existing camera in replace mode.
  28712. if (replace) {
  28713. if (this.activeCamera) {
  28714. this.activeCamera.dispose();
  28715. this.activeCamera = null;
  28716. }
  28717. }
  28718. // Camera
  28719. if (!this.activeCamera) {
  28720. var worldExtends = this.getWorldExtends();
  28721. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28722. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28723. var camera;
  28724. var radius = worldSize.length() * 1.5;
  28725. // empty scene scenario!
  28726. if (!isFinite(radius)) {
  28727. radius = 1;
  28728. worldCenter.copyFromFloats(0, 0, 0);
  28729. }
  28730. if (createArcRotateCamera) {
  28731. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28732. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28733. arcRotateCamera.wheelPrecision = 100 / radius;
  28734. camera = arcRotateCamera;
  28735. }
  28736. else {
  28737. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28738. freeCamera.setTarget(worldCenter);
  28739. camera = freeCamera;
  28740. }
  28741. camera.minZ = radius * 0.01;
  28742. camera.maxZ = radius * 1000;
  28743. camera.speed = radius * 0.2;
  28744. this.activeCamera = camera;
  28745. var canvas = this.getEngine().getRenderingCanvas();
  28746. if (attachCameraControls && canvas) {
  28747. camera.attachControl(canvas);
  28748. }
  28749. }
  28750. };
  28751. /**
  28752. * Creates a default camera and a default light
  28753. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28754. * @param replace defines if the camera and/or light will replace the existing ones
  28755. * @param attachCameraControls defines if attachControl will be called on the new camera
  28756. */
  28757. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28758. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28759. if (replace === void 0) { replace = false; }
  28760. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28761. this.createDefaultLight(replace);
  28762. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28763. };
  28764. /**
  28765. * Creates a new sky box
  28766. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28767. * @param environmentTexture defines the texture to use as environment texture
  28768. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28769. * @param scale defines the overall scale of the skybox
  28770. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28771. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28772. * @returns a new mesh holding the sky box
  28773. */
  28774. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28775. if (pbr === void 0) { pbr = false; }
  28776. if (scale === void 0) { scale = 1000; }
  28777. if (blur === void 0) { blur = 0; }
  28778. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28779. if (!environmentTexture) {
  28780. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28781. return null;
  28782. }
  28783. if (setGlobalEnvTexture) {
  28784. if (environmentTexture) {
  28785. this.environmentTexture = environmentTexture;
  28786. }
  28787. }
  28788. // Skybox
  28789. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28790. if (pbr) {
  28791. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28792. hdrSkyboxMaterial.backFaceCulling = false;
  28793. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28794. if (hdrSkyboxMaterial.reflectionTexture) {
  28795. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28796. }
  28797. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28798. hdrSkyboxMaterial.disableLighting = true;
  28799. hdrSkyboxMaterial.twoSidedLighting = true;
  28800. hdrSkybox.infiniteDistance = true;
  28801. hdrSkybox.material = hdrSkyboxMaterial;
  28802. }
  28803. else {
  28804. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28805. skyboxMaterial.backFaceCulling = false;
  28806. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28807. if (skyboxMaterial.reflectionTexture) {
  28808. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28809. }
  28810. skyboxMaterial.disableLighting = true;
  28811. hdrSkybox.infiniteDistance = true;
  28812. hdrSkybox.material = skyboxMaterial;
  28813. }
  28814. return hdrSkybox;
  28815. };
  28816. /**
  28817. * Creates a new environment
  28818. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28819. * @param options defines the options you can use to configure the environment
  28820. * @returns the new EnvironmentHelper
  28821. */
  28822. Scene.prototype.createDefaultEnvironment = function (options) {
  28823. if (BABYLON.EnvironmentHelper) {
  28824. return new BABYLON.EnvironmentHelper(options, this);
  28825. }
  28826. return null;
  28827. };
  28828. /**
  28829. * Creates a new VREXperienceHelper
  28830. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28831. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28832. * @returns a new VREXperienceHelper
  28833. */
  28834. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28835. if (webVROptions === void 0) { webVROptions = {}; }
  28836. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28837. };
  28838. // Tags
  28839. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28840. if (tagsQuery === undefined) {
  28841. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28842. return list;
  28843. }
  28844. var listByTags = [];
  28845. forEach = forEach || (function (item) { return; });
  28846. for (var i in list) {
  28847. var item = list[i];
  28848. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28849. listByTags.push(item);
  28850. forEach(item);
  28851. }
  28852. }
  28853. return listByTags;
  28854. };
  28855. /**
  28856. * Get a list of meshes by tags
  28857. * @param tagsQuery defines the tags query to use
  28858. * @param forEach defines a predicate used to filter results
  28859. * @returns an array of Mesh
  28860. */
  28861. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28862. return this._getByTags(this.meshes, tagsQuery, forEach);
  28863. };
  28864. /**
  28865. * Get a list of cameras by tags
  28866. * @param tagsQuery defines the tags query to use
  28867. * @param forEach defines a predicate used to filter results
  28868. * @returns an array of Camera
  28869. */
  28870. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28871. return this._getByTags(this.cameras, tagsQuery, forEach);
  28872. };
  28873. /**
  28874. * Get a list of lights by tags
  28875. * @param tagsQuery defines the tags query to use
  28876. * @param forEach defines a predicate used to filter results
  28877. * @returns an array of Light
  28878. */
  28879. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28880. return this._getByTags(this.lights, tagsQuery, forEach);
  28881. };
  28882. /**
  28883. * Get a list of materials by tags
  28884. * @param tagsQuery defines the tags query to use
  28885. * @param forEach defines a predicate used to filter results
  28886. * @returns an array of Material
  28887. */
  28888. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28889. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28890. };
  28891. /**
  28892. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28893. * This allowed control for front to back rendering or reversly depending of the special needs.
  28894. *
  28895. * @param renderingGroupId The rendering group id corresponding to its index
  28896. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28897. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28898. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28899. */
  28900. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28901. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28902. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28903. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28904. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28905. };
  28906. /**
  28907. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28908. *
  28909. * @param renderingGroupId The rendering group id corresponding to its index
  28910. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28911. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28912. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28913. */
  28914. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28915. if (depth === void 0) { depth = true; }
  28916. if (stencil === void 0) { stencil = true; }
  28917. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28918. };
  28919. /**
  28920. * Will flag all materials as dirty to trigger new shader compilation
  28921. * @param flag defines the flag used to specify which material part must be marked as dirty
  28922. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28923. */
  28924. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28925. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28926. var material = _a[_i];
  28927. if (predicate && !predicate(material)) {
  28928. continue;
  28929. }
  28930. material.markAsDirty(flag);
  28931. }
  28932. };
  28933. /** @hidden */
  28934. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28935. var _this = this;
  28936. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28937. this._activeRequests.push(request);
  28938. request.onCompleteObservable.add(function (request) {
  28939. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28940. });
  28941. return request;
  28942. };
  28943. /** @hidden */
  28944. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28945. var _this = this;
  28946. return new Promise(function (resolve, reject) {
  28947. _this._loadFile(url, function (data) {
  28948. resolve(data);
  28949. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28950. reject(exception);
  28951. });
  28952. });
  28953. };
  28954. // Statics
  28955. Scene._FOGMODE_NONE = 0;
  28956. Scene._FOGMODE_EXP = 1;
  28957. Scene._FOGMODE_EXP2 = 2;
  28958. Scene._FOGMODE_LINEAR = 3;
  28959. Scene._uniqueIdCounter = 0;
  28960. /**
  28961. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28962. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28963. */
  28964. Scene.MinDeltaTime = 1.0;
  28965. /**
  28966. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28967. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28968. */
  28969. Scene.MaxDeltaTime = 1000.0;
  28970. /** The distance in pixel that you have to move to prevent some events */
  28971. Scene.DragMovementThreshold = 10; // in pixels
  28972. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28973. Scene.LongPressDelay = 500; // in milliseconds
  28974. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28975. Scene.DoubleClickDelay = 300; // in milliseconds
  28976. /** If you need to check double click without raising a single click at first click, enable this flag */
  28977. Scene.ExclusiveDoubleClickMode = false;
  28978. return Scene;
  28979. }());
  28980. BABYLON.Scene = Scene;
  28981. })(BABYLON || (BABYLON = {}));
  28982. //# sourceMappingURL=babylon.scene.js.map
  28983. var BABYLON;
  28984. (function (BABYLON) {
  28985. /**
  28986. * Set of assets to keep when moving a scene into an asset container.
  28987. */
  28988. var KeepAssets = /** @class */ (function () {
  28989. function KeepAssets() {
  28990. /**
  28991. * Cameras to keep.
  28992. */
  28993. this.cameras = new Array();
  28994. /**
  28995. * Lights to keep.
  28996. */
  28997. this.lights = new Array();
  28998. /**
  28999. * Meshes to keep.
  29000. */
  29001. this.meshes = new Array();
  29002. /**
  29003. * Skeletons to keep.
  29004. */
  29005. this.skeletons = new Array();
  29006. /**
  29007. * ParticleSystems to keep.
  29008. */
  29009. this.particleSystems = new Array();
  29010. /**
  29011. * Animations to keep.
  29012. */
  29013. this.animations = new Array();
  29014. /**
  29015. * AnimationGroups to keep.
  29016. */
  29017. this.animationGroups = new Array();
  29018. /**
  29019. * MultiMaterials to keep.
  29020. */
  29021. this.multiMaterials = new Array();
  29022. /**
  29023. * Materials to keep.
  29024. */
  29025. this.materials = new Array();
  29026. /**
  29027. * MorphTargetManagers to keep.
  29028. */
  29029. this.morphTargetManagers = new Array();
  29030. /**
  29031. * Geometries to keep.
  29032. */
  29033. this.geometries = new Array();
  29034. /**
  29035. * TransformNodes to keep.
  29036. */
  29037. this.transformNodes = new Array();
  29038. /**
  29039. * LensFlareSystems to keep.
  29040. */
  29041. this.lensFlareSystems = new Array();
  29042. /**
  29043. * ShadowGenerators to keep.
  29044. */
  29045. this.shadowGenerators = new Array();
  29046. /**
  29047. * ActionManagers to keep.
  29048. */
  29049. this.actionManagers = new Array();
  29050. /**
  29051. * Sounds to keep.
  29052. */
  29053. this.sounds = new Array();
  29054. /**
  29055. * Textures to keep.
  29056. */
  29057. this.textures = new Array();
  29058. /**
  29059. * Effect layers to keep.
  29060. */
  29061. this.effectLayers = new Array();
  29062. }
  29063. return KeepAssets;
  29064. }());
  29065. BABYLON.KeepAssets = KeepAssets;
  29066. /**
  29067. * Container with a set of assets that can be added or removed from a scene.
  29068. */
  29069. var AssetContainer = /** @class */ (function () {
  29070. /**
  29071. * Instantiates an AssetContainer.
  29072. * @param scene The scene the AssetContainer belongs to.
  29073. */
  29074. function AssetContainer(scene) {
  29075. // Objects
  29076. /**
  29077. * Cameras populated in the container.
  29078. */
  29079. this.cameras = new Array();
  29080. /**
  29081. * Lights populated in the container.
  29082. */
  29083. this.lights = new Array();
  29084. /**
  29085. * Meshes populated in the container.
  29086. */
  29087. this.meshes = new Array();
  29088. /**
  29089. * Skeletons populated in the container.
  29090. */
  29091. this.skeletons = new Array();
  29092. /**
  29093. * ParticleSystems populated in the container.
  29094. */
  29095. this.particleSystems = new Array();
  29096. /**
  29097. * Animations populated in the container.
  29098. */
  29099. this.animations = new Array();
  29100. /**
  29101. * AnimationGroups populated in the container.
  29102. */
  29103. this.animationGroups = new Array();
  29104. /**
  29105. * MultiMaterials populated in the container.
  29106. */
  29107. this.multiMaterials = new Array();
  29108. /**
  29109. * Materials populated in the container.
  29110. */
  29111. this.materials = new Array();
  29112. /**
  29113. * MorphTargetManagers populated in the container.
  29114. */
  29115. this.morphTargetManagers = new Array();
  29116. /**
  29117. * Geometries populated in the container.
  29118. */
  29119. this.geometries = new Array();
  29120. /**
  29121. * TransformNodes populated in the container.
  29122. */
  29123. this.transformNodes = new Array();
  29124. /**
  29125. * LensFlareSystems populated in the container.
  29126. */
  29127. this.lensFlareSystems = new Array();
  29128. /**
  29129. * ShadowGenerators populated in the container.
  29130. */
  29131. this.shadowGenerators = new Array();
  29132. /**
  29133. * ActionManagers populated in the container.
  29134. */
  29135. this.actionManagers = new Array();
  29136. /**
  29137. * Sounds populated in the container.
  29138. */
  29139. this.sounds = new Array();
  29140. /**
  29141. * Textures populated in the container.
  29142. */
  29143. this.textures = new Array();
  29144. /**
  29145. * Effect layers populated in the container.
  29146. */
  29147. this.effectLayers = new Array();
  29148. this.scene = scene;
  29149. }
  29150. /**
  29151. * Adds all the assets from the container to the scene.
  29152. */
  29153. AssetContainer.prototype.addAllToScene = function () {
  29154. var _this = this;
  29155. this.cameras.forEach(function (o) {
  29156. _this.scene.addCamera(o);
  29157. });
  29158. this.lights.forEach(function (o) {
  29159. _this.scene.addLight(o);
  29160. });
  29161. this.meshes.forEach(function (o) {
  29162. _this.scene.addMesh(o);
  29163. });
  29164. this.skeletons.forEach(function (o) {
  29165. _this.scene.addSkeleton(o);
  29166. });
  29167. this.particleSystems.forEach(function (o) {
  29168. _this.scene.addParticleSystem(o);
  29169. });
  29170. this.animations.forEach(function (o) {
  29171. _this.scene.addAnimation(o);
  29172. });
  29173. this.animationGroups.forEach(function (o) {
  29174. _this.scene.addAnimationGroup(o);
  29175. });
  29176. this.multiMaterials.forEach(function (o) {
  29177. _this.scene.addMultiMaterial(o);
  29178. });
  29179. this.materials.forEach(function (o) {
  29180. _this.scene.addMaterial(o);
  29181. });
  29182. this.morphTargetManagers.forEach(function (o) {
  29183. _this.scene.addMorphTargetManager(o);
  29184. });
  29185. this.geometries.forEach(function (o) {
  29186. _this.scene.addGeometry(o);
  29187. });
  29188. this.transformNodes.forEach(function (o) {
  29189. _this.scene.addTransformNode(o);
  29190. });
  29191. this.lensFlareSystems.forEach(function (o) {
  29192. _this.scene.addLensFlareSystem(o);
  29193. });
  29194. this.actionManagers.forEach(function (o) {
  29195. _this.scene.addActionManager(o);
  29196. });
  29197. this.sounds.forEach(function (o) {
  29198. o.play();
  29199. o.autoplay = true;
  29200. _this.scene.mainSoundTrack.AddSound(o);
  29201. });
  29202. this.textures.forEach(function (o) {
  29203. _this.scene.addTexture(o);
  29204. });
  29205. this.effectLayers.forEach(function (o) {
  29206. _this.scene.addEffectLayer(o);
  29207. });
  29208. };
  29209. /**
  29210. * Removes all the assets in the container from the scene
  29211. */
  29212. AssetContainer.prototype.removeAllFromScene = function () {
  29213. var _this = this;
  29214. this.cameras.forEach(function (o) {
  29215. _this.scene.removeCamera(o);
  29216. });
  29217. this.lights.forEach(function (o) {
  29218. _this.scene.removeLight(o);
  29219. });
  29220. this.meshes.forEach(function (o) {
  29221. _this.scene.removeMesh(o);
  29222. });
  29223. this.skeletons.forEach(function (o) {
  29224. _this.scene.removeSkeleton(o);
  29225. });
  29226. this.particleSystems.forEach(function (o) {
  29227. _this.scene.removeParticleSystem(o);
  29228. });
  29229. this.animations.forEach(function (o) {
  29230. _this.scene.removeAnimation(o);
  29231. });
  29232. this.animationGroups.forEach(function (o) {
  29233. _this.scene.removeAnimationGroup(o);
  29234. });
  29235. this.multiMaterials.forEach(function (o) {
  29236. _this.scene.removeMultiMaterial(o);
  29237. });
  29238. this.materials.forEach(function (o) {
  29239. _this.scene.removeMaterial(o);
  29240. });
  29241. this.morphTargetManagers.forEach(function (o) {
  29242. _this.scene.removeMorphTargetManager(o);
  29243. });
  29244. this.geometries.forEach(function (o) {
  29245. _this.scene.removeGeometry(o);
  29246. });
  29247. this.transformNodes.forEach(function (o) {
  29248. _this.scene.removeTransformNode(o);
  29249. });
  29250. this.lensFlareSystems.forEach(function (o) {
  29251. _this.scene.removeLensFlareSystem(o);
  29252. });
  29253. this.actionManagers.forEach(function (o) {
  29254. _this.scene.removeActionManager(o);
  29255. });
  29256. this.sounds.forEach(function (o) {
  29257. o.stop();
  29258. o.autoplay = false;
  29259. _this.scene.mainSoundTrack.RemoveSound(o);
  29260. });
  29261. this.textures.forEach(function (o) {
  29262. _this.scene.removeTexture(o);
  29263. });
  29264. this.effectLayers.forEach(function (o) {
  29265. _this.scene.removeEffectLayer(o);
  29266. });
  29267. };
  29268. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29269. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29270. var asset = sourceAssets_1[_i];
  29271. var move = true;
  29272. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29273. var keepAsset = keepAssets_1[_a];
  29274. if (asset === keepAsset) {
  29275. move = false;
  29276. break;
  29277. }
  29278. }
  29279. if (move) {
  29280. targetAssets.push(asset);
  29281. }
  29282. }
  29283. };
  29284. /**
  29285. * Removes all the assets contained in the scene and adds them to the container.
  29286. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29287. */
  29288. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29289. if (keepAssets === undefined) {
  29290. keepAssets = new KeepAssets();
  29291. }
  29292. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29293. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29294. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29295. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29296. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29297. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29298. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29299. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29300. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29301. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29302. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29303. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29304. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29305. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29306. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29307. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29308. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29309. this.removeAllFromScene();
  29310. };
  29311. /**
  29312. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29313. * @returns the root mesh
  29314. */
  29315. AssetContainer.prototype.createRootMesh = function () {
  29316. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29317. this.meshes.forEach(function (m) {
  29318. if (!m.parent) {
  29319. rootMesh.addChild(m);
  29320. }
  29321. });
  29322. this.meshes.unshift(rootMesh);
  29323. return rootMesh;
  29324. };
  29325. return AssetContainer;
  29326. }());
  29327. BABYLON.AssetContainer = AssetContainer;
  29328. })(BABYLON || (BABYLON = {}));
  29329. //# sourceMappingURL=babylon.assetContainer.js.map
  29330. var BABYLON;
  29331. (function (BABYLON) {
  29332. var Buffer = /** @class */ (function () {
  29333. /**
  29334. * Constructor
  29335. * @param engine the engine
  29336. * @param data the data to use for this buffer
  29337. * @param updatable whether the data is updatable
  29338. * @param stride the stride (optional)
  29339. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29340. * @param instanced whether the buffer is instanced (optional)
  29341. * @param useBytes set to true if the stride in in bytes (optional)
  29342. */
  29343. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29344. if (stride === void 0) { stride = 0; }
  29345. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29346. if (instanced === void 0) { instanced = false; }
  29347. if (useBytes === void 0) { useBytes = false; }
  29348. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29349. this._engine = engine.getScene().getEngine();
  29350. }
  29351. else {
  29352. this._engine = engine;
  29353. }
  29354. this._updatable = updatable;
  29355. this._instanced = instanced;
  29356. this._data = data;
  29357. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29358. if (!postponeInternalCreation) { // by default
  29359. this.create();
  29360. }
  29361. }
  29362. /**
  29363. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29364. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29365. * @param offset defines offset in the buffer (0 by default)
  29366. * @param size defines the size in floats of attributes (position is 3 for instance)
  29367. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29368. * @param instanced defines if the vertex buffer contains indexed data
  29369. * @param useBytes defines if the offset and stride are in bytes
  29370. * @returns the new vertex buffer
  29371. */
  29372. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29373. if (useBytes === void 0) { useBytes = false; }
  29374. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29375. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29376. // a lot of these parameters are ignored as they are overriden by the buffer
  29377. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29378. };
  29379. // Properties
  29380. Buffer.prototype.isUpdatable = function () {
  29381. return this._updatable;
  29382. };
  29383. Buffer.prototype.getData = function () {
  29384. return this._data;
  29385. };
  29386. Buffer.prototype.getBuffer = function () {
  29387. return this._buffer;
  29388. };
  29389. /**
  29390. * Gets the stride in float32 units (i.e. byte stride / 4).
  29391. * May not be an integer if the byte stride is not divisible by 4.
  29392. * DEPRECATED. Use byteStride instead.
  29393. * @returns the stride in float32 units
  29394. */
  29395. Buffer.prototype.getStrideSize = function () {
  29396. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29397. };
  29398. // Methods
  29399. Buffer.prototype.create = function (data) {
  29400. if (data === void 0) { data = null; }
  29401. if (!data && this._buffer) {
  29402. return; // nothing to do
  29403. }
  29404. data = data || this._data;
  29405. if (!data) {
  29406. return;
  29407. }
  29408. if (!this._buffer) { // create buffer
  29409. if (this._updatable) {
  29410. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29411. this._data = data;
  29412. }
  29413. else {
  29414. this._buffer = this._engine.createVertexBuffer(data);
  29415. }
  29416. }
  29417. else if (this._updatable) { // update buffer
  29418. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29419. this._data = data;
  29420. }
  29421. };
  29422. Buffer.prototype._rebuild = function () {
  29423. this._buffer = null;
  29424. this.create(this._data);
  29425. };
  29426. Buffer.prototype.update = function (data) {
  29427. this.create(data);
  29428. };
  29429. /**
  29430. * Updates the data directly.
  29431. * @param data the new data
  29432. * @param offset the new offset
  29433. * @param vertexCount the vertex count (optional)
  29434. * @param useBytes set to true if the offset is in bytes
  29435. */
  29436. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29437. if (useBytes === void 0) { useBytes = false; }
  29438. if (!this._buffer) {
  29439. return;
  29440. }
  29441. if (this._updatable) { // update buffer
  29442. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29443. this._data = null;
  29444. }
  29445. };
  29446. Buffer.prototype.dispose = function () {
  29447. if (!this._buffer) {
  29448. return;
  29449. }
  29450. if (this._engine._releaseBuffer(this._buffer)) {
  29451. this._buffer = null;
  29452. }
  29453. };
  29454. return Buffer;
  29455. }());
  29456. BABYLON.Buffer = Buffer;
  29457. })(BABYLON || (BABYLON = {}));
  29458. //# sourceMappingURL=babylon.buffer.js.map
  29459. var BABYLON;
  29460. (function (BABYLON) {
  29461. var VertexBuffer = /** @class */ (function () {
  29462. /**
  29463. * Constructor
  29464. * @param engine the engine
  29465. * @param data the data to use for this vertex buffer
  29466. * @param kind the vertex buffer kind
  29467. * @param updatable whether the data is updatable
  29468. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29469. * @param stride the stride (optional)
  29470. * @param instanced whether the buffer is instanced (optional)
  29471. * @param offset the offset of the data (optional)
  29472. * @param size the number of components (optional)
  29473. * @param type the type of the component (optional)
  29474. * @param normalized whether the data contains normalized data (optional)
  29475. * @param useBytes set to true if stride and offset are in bytes (optional)
  29476. */
  29477. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29478. if (normalized === void 0) { normalized = false; }
  29479. if (useBytes === void 0) { useBytes = false; }
  29480. if (data instanceof BABYLON.Buffer) {
  29481. this._buffer = data;
  29482. this._ownsBuffer = false;
  29483. }
  29484. else {
  29485. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29486. this._ownsBuffer = true;
  29487. }
  29488. this._kind = kind;
  29489. if (type == undefined) {
  29490. var data_1 = this.getData();
  29491. this.type = VertexBuffer.FLOAT;
  29492. if (data_1 instanceof Int8Array)
  29493. this.type = VertexBuffer.BYTE;
  29494. else if (data_1 instanceof Uint8Array)
  29495. this.type = VertexBuffer.UNSIGNED_BYTE;
  29496. else if (data_1 instanceof Int16Array)
  29497. this.type = VertexBuffer.SHORT;
  29498. else if (data_1 instanceof Uint16Array)
  29499. this.type = VertexBuffer.UNSIGNED_SHORT;
  29500. else if (data_1 instanceof Int32Array)
  29501. this.type = VertexBuffer.INT;
  29502. else if (data_1 instanceof Uint32Array)
  29503. this.type = VertexBuffer.UNSIGNED_INT;
  29504. }
  29505. else {
  29506. this.type = type;
  29507. }
  29508. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29509. if (useBytes) {
  29510. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29511. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29512. this.byteOffset = offset || 0;
  29513. }
  29514. else {
  29515. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29516. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29517. this.byteOffset = (offset || 0) * typeByteLength;
  29518. }
  29519. this.normalized = normalized;
  29520. this._instanced = instanced !== undefined ? instanced : false;
  29521. this._instanceDivisor = instanced ? 1 : 0;
  29522. }
  29523. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29524. /**
  29525. * Gets or sets the instance divisor when in instanced mode
  29526. */
  29527. get: function () {
  29528. return this._instanceDivisor;
  29529. },
  29530. set: function (value) {
  29531. this._instanceDivisor = value;
  29532. if (value == 0) {
  29533. this._instanced = false;
  29534. }
  29535. else {
  29536. this._instanced = true;
  29537. }
  29538. },
  29539. enumerable: true,
  29540. configurable: true
  29541. });
  29542. VertexBuffer.prototype._rebuild = function () {
  29543. if (!this._buffer) {
  29544. return;
  29545. }
  29546. this._buffer._rebuild();
  29547. };
  29548. /**
  29549. * Returns the kind of the VertexBuffer (string).
  29550. */
  29551. VertexBuffer.prototype.getKind = function () {
  29552. return this._kind;
  29553. };
  29554. // Properties
  29555. /**
  29556. * Boolean : is the VertexBuffer updatable ?
  29557. */
  29558. VertexBuffer.prototype.isUpdatable = function () {
  29559. return this._buffer.isUpdatable();
  29560. };
  29561. /**
  29562. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29563. */
  29564. VertexBuffer.prototype.getData = function () {
  29565. return this._buffer.getData();
  29566. };
  29567. /**
  29568. * Returns the WebGLBuffer associated to the VertexBuffer.
  29569. */
  29570. VertexBuffer.prototype.getBuffer = function () {
  29571. return this._buffer.getBuffer();
  29572. };
  29573. /**
  29574. * Returns the stride as a multiple of the type byte length.
  29575. * DEPRECATED. Use byteStride instead.
  29576. */
  29577. VertexBuffer.prototype.getStrideSize = function () {
  29578. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29579. };
  29580. /**
  29581. * Returns the offset as a multiple of the type byte length.
  29582. * DEPRECATED. Use byteOffset instead.
  29583. */
  29584. VertexBuffer.prototype.getOffset = function () {
  29585. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29586. };
  29587. /**
  29588. * Returns the number of components per vertex attribute (integer).
  29589. */
  29590. VertexBuffer.prototype.getSize = function () {
  29591. return this._size;
  29592. };
  29593. /**
  29594. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29595. */
  29596. VertexBuffer.prototype.getIsInstanced = function () {
  29597. return this._instanced;
  29598. };
  29599. /**
  29600. * Returns the instancing divisor, zero for non-instanced (integer).
  29601. */
  29602. VertexBuffer.prototype.getInstanceDivisor = function () {
  29603. return this._instanceDivisor;
  29604. };
  29605. // Methods
  29606. /**
  29607. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29608. * Returns the created WebGLBuffer.
  29609. */
  29610. VertexBuffer.prototype.create = function (data) {
  29611. return this._buffer.create(data);
  29612. };
  29613. /**
  29614. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29615. * This function will create a new buffer if the current one is not updatable
  29616. * Returns the updated WebGLBuffer.
  29617. */
  29618. VertexBuffer.prototype.update = function (data) {
  29619. return this._buffer.update(data);
  29620. };
  29621. /**
  29622. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29623. * Returns the directly updated WebGLBuffer.
  29624. * @param data the new data
  29625. * @param offset the new offset
  29626. * @param useBytes set to true if the offset is in bytes
  29627. */
  29628. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29629. if (useBytes === void 0) { useBytes = false; }
  29630. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29631. };
  29632. /**
  29633. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29634. */
  29635. VertexBuffer.prototype.dispose = function () {
  29636. if (this._ownsBuffer) {
  29637. this._buffer.dispose();
  29638. }
  29639. };
  29640. /**
  29641. * Enumerates each value of this vertex buffer as numbers.
  29642. * @param count the number of values to enumerate
  29643. * @param callback the callback function called for each value
  29644. */
  29645. VertexBuffer.prototype.forEach = function (count, callback) {
  29646. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29647. };
  29648. Object.defineProperty(VertexBuffer, "PositionKind", {
  29649. get: function () {
  29650. return VertexBuffer._PositionKind;
  29651. },
  29652. enumerable: true,
  29653. configurable: true
  29654. });
  29655. Object.defineProperty(VertexBuffer, "NormalKind", {
  29656. get: function () {
  29657. return VertexBuffer._NormalKind;
  29658. },
  29659. enumerable: true,
  29660. configurable: true
  29661. });
  29662. Object.defineProperty(VertexBuffer, "TangentKind", {
  29663. get: function () {
  29664. return VertexBuffer._TangentKind;
  29665. },
  29666. enumerable: true,
  29667. configurable: true
  29668. });
  29669. Object.defineProperty(VertexBuffer, "UVKind", {
  29670. get: function () {
  29671. return VertexBuffer._UVKind;
  29672. },
  29673. enumerable: true,
  29674. configurable: true
  29675. });
  29676. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29677. get: function () {
  29678. return VertexBuffer._UV2Kind;
  29679. },
  29680. enumerable: true,
  29681. configurable: true
  29682. });
  29683. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29684. get: function () {
  29685. return VertexBuffer._UV3Kind;
  29686. },
  29687. enumerable: true,
  29688. configurable: true
  29689. });
  29690. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29691. get: function () {
  29692. return VertexBuffer._UV4Kind;
  29693. },
  29694. enumerable: true,
  29695. configurable: true
  29696. });
  29697. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29698. get: function () {
  29699. return VertexBuffer._UV5Kind;
  29700. },
  29701. enumerable: true,
  29702. configurable: true
  29703. });
  29704. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29705. get: function () {
  29706. return VertexBuffer._UV6Kind;
  29707. },
  29708. enumerable: true,
  29709. configurable: true
  29710. });
  29711. Object.defineProperty(VertexBuffer, "ColorKind", {
  29712. get: function () {
  29713. return VertexBuffer._ColorKind;
  29714. },
  29715. enumerable: true,
  29716. configurable: true
  29717. });
  29718. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29719. get: function () {
  29720. return VertexBuffer._MatricesIndicesKind;
  29721. },
  29722. enumerable: true,
  29723. configurable: true
  29724. });
  29725. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29726. get: function () {
  29727. return VertexBuffer._MatricesWeightsKind;
  29728. },
  29729. enumerable: true,
  29730. configurable: true
  29731. });
  29732. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29733. get: function () {
  29734. return VertexBuffer._MatricesIndicesExtraKind;
  29735. },
  29736. enumerable: true,
  29737. configurable: true
  29738. });
  29739. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29740. get: function () {
  29741. return VertexBuffer._MatricesWeightsExtraKind;
  29742. },
  29743. enumerable: true,
  29744. configurable: true
  29745. });
  29746. /**
  29747. * Deduces the stride given a kind.
  29748. * @param kind The kind string to deduce
  29749. * @returns The deduced stride
  29750. */
  29751. VertexBuffer.DeduceStride = function (kind) {
  29752. switch (kind) {
  29753. case VertexBuffer.UVKind:
  29754. case VertexBuffer.UV2Kind:
  29755. case VertexBuffer.UV3Kind:
  29756. case VertexBuffer.UV4Kind:
  29757. case VertexBuffer.UV5Kind:
  29758. case VertexBuffer.UV6Kind:
  29759. return 2;
  29760. case VertexBuffer.NormalKind:
  29761. case VertexBuffer.PositionKind:
  29762. return 3;
  29763. case VertexBuffer.ColorKind:
  29764. case VertexBuffer.MatricesIndicesKind:
  29765. case VertexBuffer.MatricesIndicesExtraKind:
  29766. case VertexBuffer.MatricesWeightsKind:
  29767. case VertexBuffer.MatricesWeightsExtraKind:
  29768. case VertexBuffer.TangentKind:
  29769. return 4;
  29770. default:
  29771. throw new Error("Invalid kind '" + kind + "'");
  29772. }
  29773. };
  29774. /**
  29775. * Gets the byte length of the given type.
  29776. * @param type the type
  29777. * @returns the number of bytes
  29778. */
  29779. VertexBuffer.GetTypeByteLength = function (type) {
  29780. switch (type) {
  29781. case VertexBuffer.BYTE:
  29782. case VertexBuffer.UNSIGNED_BYTE:
  29783. return 1;
  29784. case VertexBuffer.SHORT:
  29785. case VertexBuffer.UNSIGNED_SHORT:
  29786. return 2;
  29787. case VertexBuffer.INT:
  29788. case VertexBuffer.FLOAT:
  29789. return 4;
  29790. default:
  29791. throw new Error("Invalid type '" + type + "'");
  29792. }
  29793. };
  29794. /**
  29795. * Enumerates each value of the given parameters as numbers.
  29796. * @param data the data to enumerate
  29797. * @param byteOffset the byte offset of the data
  29798. * @param byteStride the byte stride of the data
  29799. * @param componentCount the number of components per element
  29800. * @param componentType the type of the component
  29801. * @param count the total number of components
  29802. * @param normalized whether the data is normalized
  29803. * @param callback the callback function called for each value
  29804. */
  29805. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29806. if (data instanceof Array) {
  29807. var offset = byteOffset / 4;
  29808. var stride = byteStride / 4;
  29809. for (var index = 0; index < count; index += componentCount) {
  29810. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29811. callback(data[offset + componentIndex], index + componentIndex);
  29812. }
  29813. offset += stride;
  29814. }
  29815. }
  29816. else {
  29817. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29818. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29819. for (var index = 0; index < count; index += componentCount) {
  29820. var componentByteOffset = byteOffset;
  29821. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29822. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29823. callback(value, index + componentIndex);
  29824. componentByteOffset += componentByteLength;
  29825. }
  29826. byteOffset += byteStride;
  29827. }
  29828. }
  29829. };
  29830. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29831. switch (type) {
  29832. case VertexBuffer.BYTE: {
  29833. var value = dataView.getInt8(byteOffset);
  29834. if (normalized) {
  29835. value = Math.max(value / 127, -1);
  29836. }
  29837. return value;
  29838. }
  29839. case VertexBuffer.UNSIGNED_BYTE: {
  29840. var value = dataView.getUint8(byteOffset);
  29841. if (normalized) {
  29842. value = value / 255;
  29843. }
  29844. return value;
  29845. }
  29846. case VertexBuffer.SHORT: {
  29847. var value = dataView.getInt16(byteOffset, true);
  29848. if (normalized) {
  29849. value = Math.max(value / 16383, -1);
  29850. }
  29851. return value;
  29852. }
  29853. case VertexBuffer.UNSIGNED_SHORT: {
  29854. var value = dataView.getUint16(byteOffset, true);
  29855. if (normalized) {
  29856. value = value / 65535;
  29857. }
  29858. return value;
  29859. }
  29860. case VertexBuffer.FLOAT: {
  29861. return dataView.getFloat32(byteOffset, true);
  29862. }
  29863. default: {
  29864. throw new Error("Invalid component type " + type);
  29865. }
  29866. }
  29867. };
  29868. /**
  29869. * The byte type.
  29870. */
  29871. VertexBuffer.BYTE = 5120;
  29872. /**
  29873. * The unsigned byte type.
  29874. */
  29875. VertexBuffer.UNSIGNED_BYTE = 5121;
  29876. /**
  29877. * The short type.
  29878. */
  29879. VertexBuffer.SHORT = 5122;
  29880. /**
  29881. * The unsigned short type.
  29882. */
  29883. VertexBuffer.UNSIGNED_SHORT = 5123;
  29884. /**
  29885. * The integer type.
  29886. */
  29887. VertexBuffer.INT = 5124;
  29888. /**
  29889. * The unsigned integer type.
  29890. */
  29891. VertexBuffer.UNSIGNED_INT = 5125;
  29892. /**
  29893. * The float type.
  29894. */
  29895. VertexBuffer.FLOAT = 5126;
  29896. // Enums
  29897. VertexBuffer._PositionKind = "position";
  29898. VertexBuffer._NormalKind = "normal";
  29899. VertexBuffer._TangentKind = "tangent";
  29900. VertexBuffer._UVKind = "uv";
  29901. VertexBuffer._UV2Kind = "uv2";
  29902. VertexBuffer._UV3Kind = "uv3";
  29903. VertexBuffer._UV4Kind = "uv4";
  29904. VertexBuffer._UV5Kind = "uv5";
  29905. VertexBuffer._UV6Kind = "uv6";
  29906. VertexBuffer._ColorKind = "color";
  29907. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29908. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29909. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29910. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29911. return VertexBuffer;
  29912. }());
  29913. BABYLON.VertexBuffer = VertexBuffer;
  29914. })(BABYLON || (BABYLON = {}));
  29915. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29916. var BABYLON;
  29917. (function (BABYLON) {
  29918. /**
  29919. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29920. */
  29921. var DummyInternalTextureTracker = /** @class */ (function () {
  29922. function DummyInternalTextureTracker() {
  29923. /**
  29924. * Gets or set the previous tracker in the list
  29925. */
  29926. this.previous = null;
  29927. /**
  29928. * Gets or set the next tracker in the list
  29929. */
  29930. this.next = null;
  29931. }
  29932. return DummyInternalTextureTracker;
  29933. }());
  29934. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29935. })(BABYLON || (BABYLON = {}));
  29936. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29937. var BABYLON;
  29938. (function (BABYLON) {
  29939. /**
  29940. * Class used to store data associated with WebGL texture data for the engine
  29941. * This class should not be used directly
  29942. */
  29943. var InternalTexture = /** @class */ (function () {
  29944. /**
  29945. * Creates a new InternalTexture
  29946. * @param engine defines the engine to use
  29947. * @param dataSource defines the type of data that will be used
  29948. */
  29949. function InternalTexture(engine, dataSource) {
  29950. /**
  29951. * Observable called when the texture is loaded
  29952. */
  29953. this.onLoadedObservable = new BABYLON.Observable();
  29954. /**
  29955. * Gets or set the previous tracker in the list
  29956. */
  29957. this.previous = null;
  29958. /**
  29959. * Gets or set the next tracker in the list
  29960. */
  29961. this.next = null;
  29962. // Private
  29963. /** @hidden */
  29964. this._initialSlot = -1;
  29965. /** @hidden */
  29966. this._designatedSlot = -1;
  29967. /** @hidden */
  29968. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29969. /** @hidden */
  29970. this._comparisonFunction = 0;
  29971. /** @hidden */
  29972. this._references = 1;
  29973. this._engine = engine;
  29974. this._dataSource = dataSource;
  29975. this._webGLTexture = engine._createTexture();
  29976. }
  29977. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29978. /**
  29979. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29980. */
  29981. get: function () {
  29982. return this._dataSource;
  29983. },
  29984. enumerable: true,
  29985. configurable: true
  29986. });
  29987. /**
  29988. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29989. */
  29990. InternalTexture.prototype.incrementReferences = function () {
  29991. this._references++;
  29992. };
  29993. /**
  29994. * Change the size of the texture (not the size of the content)
  29995. * @param width defines the new width
  29996. * @param height defines the new height
  29997. * @param depth defines the new depth (1 by default)
  29998. */
  29999. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30000. if (depth === void 0) { depth = 1; }
  30001. this.width = width;
  30002. this.height = height;
  30003. this.depth = depth;
  30004. this.baseWidth = width;
  30005. this.baseHeight = height;
  30006. this.baseDepth = depth;
  30007. this._size = width * height * depth;
  30008. };
  30009. /** @hidden */
  30010. InternalTexture.prototype._rebuild = function () {
  30011. var _this = this;
  30012. var proxy;
  30013. this.isReady = false;
  30014. this._cachedCoordinatesMode = null;
  30015. this._cachedWrapU = null;
  30016. this._cachedWrapV = null;
  30017. this._cachedAnisotropicFilteringLevel = null;
  30018. switch (this._dataSource) {
  30019. case InternalTexture.DATASOURCE_TEMP:
  30020. return;
  30021. case InternalTexture.DATASOURCE_URL:
  30022. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30023. _this.isReady = true;
  30024. }, null, this._buffer, undefined, this.format);
  30025. proxy._swapAndDie(this);
  30026. return;
  30027. case InternalTexture.DATASOURCE_RAW:
  30028. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30029. proxy._swapAndDie(this);
  30030. this.isReady = true;
  30031. return;
  30032. case InternalTexture.DATASOURCE_RAW3D:
  30033. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30034. proxy._swapAndDie(this);
  30035. this.isReady = true;
  30036. return;
  30037. case InternalTexture.DATASOURCE_DYNAMIC:
  30038. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30039. proxy._swapAndDie(this);
  30040. // The engine will make sure to update content so no need to flag it as isReady = true
  30041. return;
  30042. case InternalTexture.DATASOURCE_RENDERTARGET:
  30043. var options = new BABYLON.RenderTargetCreationOptions();
  30044. options.generateDepthBuffer = this._generateDepthBuffer;
  30045. options.generateMipMaps = this.generateMipMaps;
  30046. options.generateStencilBuffer = this._generateStencilBuffer;
  30047. options.samplingMode = this.samplingMode;
  30048. options.type = this.type;
  30049. if (this.isCube) {
  30050. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30051. }
  30052. else {
  30053. var size = {
  30054. width: this.width,
  30055. height: this.height
  30056. };
  30057. proxy = this._engine.createRenderTargetTexture(size, options);
  30058. }
  30059. proxy._swapAndDie(this);
  30060. this.isReady = true;
  30061. return;
  30062. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30063. var depthTextureOptions = {
  30064. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30065. comparisonFunction: this._comparisonFunction,
  30066. generateStencil: this._generateStencilBuffer,
  30067. isCube: this.isCube
  30068. };
  30069. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30070. proxy._swapAndDie(this);
  30071. this.isReady = true;
  30072. return;
  30073. case InternalTexture.DATASOURCE_CUBE:
  30074. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30075. _this.isReady = true;
  30076. }, null, this.format, this._extension);
  30077. proxy._swapAndDie(this);
  30078. return;
  30079. case InternalTexture.DATASOURCE_CUBERAW:
  30080. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30081. proxy._swapAndDie(this);
  30082. this.isReady = true;
  30083. return;
  30084. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30085. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30086. if (proxy) {
  30087. proxy._swapAndDie(_this);
  30088. }
  30089. _this.isReady = true;
  30090. }, null, this.format, this._extension);
  30091. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30092. return;
  30093. }
  30094. };
  30095. InternalTexture.prototype._swapAndDie = function (target) {
  30096. target._webGLTexture = this._webGLTexture;
  30097. if (this._framebuffer) {
  30098. target._framebuffer = this._framebuffer;
  30099. }
  30100. if (this._depthStencilBuffer) {
  30101. target._depthStencilBuffer = this._depthStencilBuffer;
  30102. }
  30103. if (this._lodTextureHigh) {
  30104. if (target._lodTextureHigh) {
  30105. target._lodTextureHigh.dispose();
  30106. }
  30107. target._lodTextureHigh = this._lodTextureHigh;
  30108. }
  30109. if (this._lodTextureMid) {
  30110. if (target._lodTextureMid) {
  30111. target._lodTextureMid.dispose();
  30112. }
  30113. target._lodTextureMid = this._lodTextureMid;
  30114. }
  30115. if (this._lodTextureLow) {
  30116. if (target._lodTextureLow) {
  30117. target._lodTextureLow.dispose();
  30118. }
  30119. target._lodTextureLow = this._lodTextureLow;
  30120. }
  30121. var cache = this._engine.getLoadedTexturesCache();
  30122. var index = cache.indexOf(this);
  30123. if (index !== -1) {
  30124. cache.splice(index, 1);
  30125. }
  30126. };
  30127. /**
  30128. * Dispose the current allocated resources
  30129. */
  30130. InternalTexture.prototype.dispose = function () {
  30131. if (!this._webGLTexture) {
  30132. return;
  30133. }
  30134. this._references--;
  30135. if (this._references === 0) {
  30136. this._engine._releaseTexture(this);
  30137. this._webGLTexture = null;
  30138. this.previous = null;
  30139. this.next = null;
  30140. }
  30141. };
  30142. /**
  30143. * The source of the texture data is unknown
  30144. */
  30145. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30146. /**
  30147. * Texture data comes from an URL
  30148. */
  30149. InternalTexture.DATASOURCE_URL = 1;
  30150. /**
  30151. * Texture data is only used for temporary storage
  30152. */
  30153. InternalTexture.DATASOURCE_TEMP = 2;
  30154. /**
  30155. * Texture data comes from raw data (ArrayBuffer)
  30156. */
  30157. InternalTexture.DATASOURCE_RAW = 3;
  30158. /**
  30159. * Texture content is dynamic (video or dynamic texture)
  30160. */
  30161. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30162. /**
  30163. * Texture content is generated by rendering to it
  30164. */
  30165. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30166. /**
  30167. * Texture content is part of a multi render target process
  30168. */
  30169. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30170. /**
  30171. * Texture data comes from a cube data file
  30172. */
  30173. InternalTexture.DATASOURCE_CUBE = 7;
  30174. /**
  30175. * Texture data comes from a raw cube data
  30176. */
  30177. InternalTexture.DATASOURCE_CUBERAW = 8;
  30178. /**
  30179. * Texture data come from a prefiltered cube data file
  30180. */
  30181. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30182. /**
  30183. * Texture content is raw 3D data
  30184. */
  30185. InternalTexture.DATASOURCE_RAW3D = 10;
  30186. /**
  30187. * Texture content is a depth texture
  30188. */
  30189. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30190. return InternalTexture;
  30191. }());
  30192. BABYLON.InternalTexture = InternalTexture;
  30193. })(BABYLON || (BABYLON = {}));
  30194. //# sourceMappingURL=babylon.internalTexture.js.map
  30195. var BABYLON;
  30196. (function (BABYLON) {
  30197. var BaseTexture = /** @class */ (function () {
  30198. function BaseTexture(scene) {
  30199. this._hasAlpha = false;
  30200. this.getAlphaFromRGB = false;
  30201. this.level = 1;
  30202. this.coordinatesIndex = 0;
  30203. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30204. /**
  30205. * | Value | Type | Description |
  30206. * | ----- | ------------------ | ----------- |
  30207. * | 0 | CLAMP_ADDRESSMODE | |
  30208. * | 1 | WRAP_ADDRESSMODE | |
  30209. * | 2 | MIRROR_ADDRESSMODE | |
  30210. */
  30211. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30212. /**
  30213. * | Value | Type | Description |
  30214. * | ----- | ------------------ | ----------- |
  30215. * | 0 | CLAMP_ADDRESSMODE | |
  30216. * | 1 | WRAP_ADDRESSMODE | |
  30217. * | 2 | MIRROR_ADDRESSMODE | |
  30218. */
  30219. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30220. /**
  30221. * | Value | Type | Description |
  30222. * | ----- | ------------------ | ----------- |
  30223. * | 0 | CLAMP_ADDRESSMODE | |
  30224. * | 1 | WRAP_ADDRESSMODE | |
  30225. * | 2 | MIRROR_ADDRESSMODE | |
  30226. */
  30227. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30228. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30229. this.isCube = false;
  30230. this.is3D = false;
  30231. this.gammaSpace = true;
  30232. this.invertZ = false;
  30233. this.lodLevelInAlpha = false;
  30234. this.lodGenerationOffset = 0.0;
  30235. this.lodGenerationScale = 0.8;
  30236. this.isRenderTarget = false;
  30237. this.animations = new Array();
  30238. /**
  30239. * An event triggered when the texture is disposed.
  30240. */
  30241. this.onDisposeObservable = new BABYLON.Observable();
  30242. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30243. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30244. if (this._scene) {
  30245. this._scene.textures.push(this);
  30246. }
  30247. this._uid = null;
  30248. }
  30249. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30250. get: function () {
  30251. return this._hasAlpha;
  30252. },
  30253. set: function (value) {
  30254. if (this._hasAlpha === value) {
  30255. return;
  30256. }
  30257. this._hasAlpha = value;
  30258. if (this._scene) {
  30259. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30260. }
  30261. },
  30262. enumerable: true,
  30263. configurable: true
  30264. });
  30265. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30266. get: function () {
  30267. return this._coordinatesMode;
  30268. },
  30269. /**
  30270. * How a texture is mapped.
  30271. *
  30272. * | Value | Type | Description |
  30273. * | ----- | ----------------------------------- | ----------- |
  30274. * | 0 | EXPLICIT_MODE | |
  30275. * | 1 | SPHERICAL_MODE | |
  30276. * | 2 | PLANAR_MODE | |
  30277. * | 3 | CUBIC_MODE | |
  30278. * | 4 | PROJECTION_MODE | |
  30279. * | 5 | SKYBOX_MODE | |
  30280. * | 6 | INVCUBIC_MODE | |
  30281. * | 7 | EQUIRECTANGULAR_MODE | |
  30282. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30283. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30284. */
  30285. set: function (value) {
  30286. if (this._coordinatesMode === value) {
  30287. return;
  30288. }
  30289. this._coordinatesMode = value;
  30290. if (this._scene) {
  30291. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30292. }
  30293. },
  30294. enumerable: true,
  30295. configurable: true
  30296. });
  30297. Object.defineProperty(BaseTexture.prototype, "uid", {
  30298. get: function () {
  30299. if (!this._uid) {
  30300. this._uid = BABYLON.Tools.RandomId();
  30301. }
  30302. return this._uid;
  30303. },
  30304. enumerable: true,
  30305. configurable: true
  30306. });
  30307. BaseTexture.prototype.toString = function () {
  30308. return this.name;
  30309. };
  30310. BaseTexture.prototype.getClassName = function () {
  30311. return "BaseTexture";
  30312. };
  30313. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30314. set: function (callback) {
  30315. if (this._onDisposeObserver) {
  30316. this.onDisposeObservable.remove(this._onDisposeObserver);
  30317. }
  30318. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30319. },
  30320. enumerable: true,
  30321. configurable: true
  30322. });
  30323. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30324. get: function () {
  30325. return true;
  30326. },
  30327. enumerable: true,
  30328. configurable: true
  30329. });
  30330. BaseTexture.prototype.getScene = function () {
  30331. return this._scene;
  30332. };
  30333. BaseTexture.prototype.getTextureMatrix = function () {
  30334. return BABYLON.Matrix.IdentityReadOnly;
  30335. };
  30336. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30337. return BABYLON.Matrix.IdentityReadOnly;
  30338. };
  30339. BaseTexture.prototype.getInternalTexture = function () {
  30340. return this._texture;
  30341. };
  30342. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30343. return !this.isBlocking || this.isReady();
  30344. };
  30345. BaseTexture.prototype.isReady = function () {
  30346. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30347. this.delayLoad();
  30348. return false;
  30349. }
  30350. if (this._texture) {
  30351. return this._texture.isReady;
  30352. }
  30353. return false;
  30354. };
  30355. BaseTexture.prototype.getSize = function () {
  30356. if (this._texture && this._texture.width) {
  30357. return new BABYLON.Size(this._texture.width, this._texture.height);
  30358. }
  30359. if (this._texture && this._texture._size) {
  30360. return new BABYLON.Size(this._texture._size, this._texture._size);
  30361. }
  30362. return BABYLON.Size.Zero();
  30363. };
  30364. BaseTexture.prototype.getBaseSize = function () {
  30365. if (!this.isReady() || !this._texture)
  30366. return BABYLON.Size.Zero();
  30367. if (this._texture._size) {
  30368. return new BABYLON.Size(this._texture._size, this._texture._size);
  30369. }
  30370. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30371. };
  30372. BaseTexture.prototype.scale = function (ratio) {
  30373. };
  30374. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30375. get: function () {
  30376. return false;
  30377. },
  30378. enumerable: true,
  30379. configurable: true
  30380. });
  30381. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30382. if (!this._scene) {
  30383. return null;
  30384. }
  30385. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30386. for (var index = 0; index < texturesCache.length; index++) {
  30387. var texturesCacheEntry = texturesCache[index];
  30388. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30389. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30390. texturesCacheEntry.incrementReferences();
  30391. return texturesCacheEntry;
  30392. }
  30393. }
  30394. }
  30395. return null;
  30396. };
  30397. BaseTexture.prototype._rebuild = function () {
  30398. };
  30399. BaseTexture.prototype.delayLoad = function () {
  30400. };
  30401. BaseTexture.prototype.clone = function () {
  30402. return null;
  30403. };
  30404. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30405. get: function () {
  30406. if (!this._texture) {
  30407. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30408. }
  30409. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30410. },
  30411. enumerable: true,
  30412. configurable: true
  30413. });
  30414. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30415. get: function () {
  30416. if (!this._texture) {
  30417. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30418. }
  30419. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30420. },
  30421. enumerable: true,
  30422. configurable: true
  30423. });
  30424. BaseTexture.prototype.readPixels = function (faceIndex) {
  30425. if (faceIndex === void 0) { faceIndex = 0; }
  30426. if (!this._texture) {
  30427. return null;
  30428. }
  30429. var size = this.getSize();
  30430. var scene = this.getScene();
  30431. if (!scene) {
  30432. return null;
  30433. }
  30434. var engine = scene.getEngine();
  30435. if (this._texture.isCube) {
  30436. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30437. }
  30438. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30439. };
  30440. BaseTexture.prototype.releaseInternalTexture = function () {
  30441. if (this._texture) {
  30442. this._texture.dispose();
  30443. this._texture = null;
  30444. }
  30445. };
  30446. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30447. get: function () {
  30448. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30449. return null;
  30450. }
  30451. if (!this._texture._sphericalPolynomial) {
  30452. this._texture._sphericalPolynomial =
  30453. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30454. }
  30455. return this._texture._sphericalPolynomial;
  30456. },
  30457. set: function (value) {
  30458. if (this._texture) {
  30459. this._texture._sphericalPolynomial = value;
  30460. }
  30461. },
  30462. enumerable: true,
  30463. configurable: true
  30464. });
  30465. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30466. get: function () {
  30467. if (this._texture) {
  30468. return this._texture._lodTextureHigh;
  30469. }
  30470. return null;
  30471. },
  30472. enumerable: true,
  30473. configurable: true
  30474. });
  30475. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30476. get: function () {
  30477. if (this._texture) {
  30478. return this._texture._lodTextureMid;
  30479. }
  30480. return null;
  30481. },
  30482. enumerable: true,
  30483. configurable: true
  30484. });
  30485. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30486. get: function () {
  30487. if (this._texture) {
  30488. return this._texture._lodTextureLow;
  30489. }
  30490. return null;
  30491. },
  30492. enumerable: true,
  30493. configurable: true
  30494. });
  30495. BaseTexture.prototype.dispose = function () {
  30496. if (!this._scene) {
  30497. return;
  30498. }
  30499. // Animations
  30500. this._scene.stopAnimation(this);
  30501. // Remove from scene
  30502. this._scene._removePendingData(this);
  30503. var index = this._scene.textures.indexOf(this);
  30504. if (index >= 0) {
  30505. this._scene.textures.splice(index, 1);
  30506. }
  30507. if (this._texture === undefined) {
  30508. return;
  30509. }
  30510. // Release
  30511. this.releaseInternalTexture();
  30512. // Callback
  30513. this.onDisposeObservable.notifyObservers(this);
  30514. this.onDisposeObservable.clear();
  30515. };
  30516. BaseTexture.prototype.serialize = function () {
  30517. if (!this.name) {
  30518. return null;
  30519. }
  30520. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30521. // Animations
  30522. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30523. return serializationObject;
  30524. };
  30525. BaseTexture.WhenAllReady = function (textures, callback) {
  30526. var numRemaining = textures.length;
  30527. if (numRemaining === 0) {
  30528. callback();
  30529. return;
  30530. }
  30531. var _loop_1 = function () {
  30532. texture = textures[i];
  30533. if (texture.isReady()) {
  30534. if (--numRemaining === 0) {
  30535. callback();
  30536. }
  30537. }
  30538. else {
  30539. onLoadObservable = texture.onLoadObservable;
  30540. var onLoadCallback_1 = function () {
  30541. onLoadObservable.removeCallback(onLoadCallback_1);
  30542. if (--numRemaining === 0) {
  30543. callback();
  30544. }
  30545. };
  30546. onLoadObservable.add(onLoadCallback_1);
  30547. }
  30548. };
  30549. var texture, onLoadObservable;
  30550. for (var i = 0; i < textures.length; i++) {
  30551. _loop_1();
  30552. }
  30553. };
  30554. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30555. __decorate([
  30556. BABYLON.serialize()
  30557. ], BaseTexture.prototype, "name", void 0);
  30558. __decorate([
  30559. BABYLON.serialize("hasAlpha")
  30560. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30561. __decorate([
  30562. BABYLON.serialize()
  30563. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30564. __decorate([
  30565. BABYLON.serialize()
  30566. ], BaseTexture.prototype, "level", void 0);
  30567. __decorate([
  30568. BABYLON.serialize()
  30569. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30570. __decorate([
  30571. BABYLON.serialize("coordinatesMode")
  30572. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30573. __decorate([
  30574. BABYLON.serialize()
  30575. ], BaseTexture.prototype, "wrapU", void 0);
  30576. __decorate([
  30577. BABYLON.serialize()
  30578. ], BaseTexture.prototype, "wrapV", void 0);
  30579. __decorate([
  30580. BABYLON.serialize()
  30581. ], BaseTexture.prototype, "wrapR", void 0);
  30582. __decorate([
  30583. BABYLON.serialize()
  30584. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30585. __decorate([
  30586. BABYLON.serialize()
  30587. ], BaseTexture.prototype, "isCube", void 0);
  30588. __decorate([
  30589. BABYLON.serialize()
  30590. ], BaseTexture.prototype, "is3D", void 0);
  30591. __decorate([
  30592. BABYLON.serialize()
  30593. ], BaseTexture.prototype, "gammaSpace", void 0);
  30594. __decorate([
  30595. BABYLON.serialize()
  30596. ], BaseTexture.prototype, "invertZ", void 0);
  30597. __decorate([
  30598. BABYLON.serialize()
  30599. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30600. __decorate([
  30601. BABYLON.serialize()
  30602. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30603. __decorate([
  30604. BABYLON.serialize()
  30605. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30606. __decorate([
  30607. BABYLON.serialize()
  30608. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30609. return BaseTexture;
  30610. }());
  30611. BABYLON.BaseTexture = BaseTexture;
  30612. })(BABYLON || (BABYLON = {}));
  30613. //# sourceMappingURL=babylon.baseTexture.js.map
  30614. var BABYLON;
  30615. (function (BABYLON) {
  30616. var Texture = /** @class */ (function (_super) {
  30617. __extends(Texture, _super);
  30618. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30619. if (noMipmap === void 0) { noMipmap = false; }
  30620. if (invertY === void 0) { invertY = true; }
  30621. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30622. if (onLoad === void 0) { onLoad = null; }
  30623. if (onError === void 0) { onError = null; }
  30624. if (buffer === void 0) { buffer = null; }
  30625. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30626. var _this = _super.call(this, scene) || this;
  30627. _this.uOffset = 0;
  30628. _this.vOffset = 0;
  30629. _this.uScale = 1.0;
  30630. _this.vScale = 1.0;
  30631. _this.uAng = 0;
  30632. _this.vAng = 0;
  30633. _this.wAng = 0;
  30634. /**
  30635. * Defines the center of rotation (U)
  30636. */
  30637. _this.uRotationCenter = 0.5;
  30638. /**
  30639. * Defines the center of rotation (V)
  30640. */
  30641. _this.vRotationCenter = 0.5;
  30642. /**
  30643. * Defines the center of rotation (W)
  30644. */
  30645. _this.wRotationCenter = 0.5;
  30646. _this._isBlocking = true;
  30647. _this.name = url || "";
  30648. _this.url = url;
  30649. _this._noMipmap = noMipmap;
  30650. _this._invertY = invertY;
  30651. _this._samplingMode = samplingMode;
  30652. _this._buffer = buffer;
  30653. _this._deleteBuffer = deleteBuffer;
  30654. if (format) {
  30655. _this._format = format;
  30656. }
  30657. scene = _this.getScene();
  30658. if (!scene) {
  30659. return _this;
  30660. }
  30661. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30662. var load = function () {
  30663. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30664. _this.onLoadObservable.notifyObservers(_this);
  30665. }
  30666. if (onLoad) {
  30667. onLoad();
  30668. }
  30669. if (!_this.isBlocking && scene) {
  30670. scene.resetCachedMaterial();
  30671. }
  30672. };
  30673. if (!_this.url) {
  30674. _this._delayedOnLoad = load;
  30675. _this._delayedOnError = onError;
  30676. return _this;
  30677. }
  30678. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30679. if (!_this._texture) {
  30680. if (!scene.useDelayedTextureLoading) {
  30681. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30682. if (deleteBuffer) {
  30683. delete _this._buffer;
  30684. }
  30685. }
  30686. else {
  30687. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30688. _this._delayedOnLoad = load;
  30689. _this._delayedOnError = onError;
  30690. }
  30691. }
  30692. else {
  30693. if (_this._texture.isReady) {
  30694. BABYLON.Tools.SetImmediate(function () { return load(); });
  30695. }
  30696. else {
  30697. _this._texture.onLoadedObservable.add(load);
  30698. }
  30699. }
  30700. return _this;
  30701. }
  30702. Object.defineProperty(Texture.prototype, "noMipmap", {
  30703. get: function () {
  30704. return this._noMipmap;
  30705. },
  30706. enumerable: true,
  30707. configurable: true
  30708. });
  30709. Object.defineProperty(Texture.prototype, "isBlocking", {
  30710. get: function () {
  30711. return this._isBlocking;
  30712. },
  30713. set: function (value) {
  30714. this._isBlocking = value;
  30715. },
  30716. enumerable: true,
  30717. configurable: true
  30718. });
  30719. Object.defineProperty(Texture.prototype, "samplingMode", {
  30720. get: function () {
  30721. return this._samplingMode;
  30722. },
  30723. enumerable: true,
  30724. configurable: true
  30725. });
  30726. /**
  30727. * Update the url (and optional buffer) of this texture if url was null during construction.
  30728. * @param url the url of the texture
  30729. * @param buffer the buffer of the texture (defaults to null)
  30730. */
  30731. Texture.prototype.updateURL = function (url, buffer) {
  30732. if (buffer === void 0) { buffer = null; }
  30733. if (this.url) {
  30734. throw new Error("URL is already set");
  30735. }
  30736. this.url = url;
  30737. this._buffer = buffer;
  30738. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30739. this.delayLoad();
  30740. };
  30741. Texture.prototype.delayLoad = function () {
  30742. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30743. return;
  30744. }
  30745. var scene = this.getScene();
  30746. if (!scene) {
  30747. return;
  30748. }
  30749. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30750. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30751. if (!this._texture) {
  30752. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30753. if (this._deleteBuffer) {
  30754. delete this._buffer;
  30755. }
  30756. }
  30757. else {
  30758. if (this._delayedOnLoad) {
  30759. if (this._texture.isReady) {
  30760. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30761. }
  30762. else {
  30763. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30764. }
  30765. }
  30766. }
  30767. this._delayedOnLoad = null;
  30768. this._delayedOnError = null;
  30769. };
  30770. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30771. if (!this._texture) {
  30772. return;
  30773. }
  30774. var scene = this.getScene();
  30775. if (!scene) {
  30776. return;
  30777. }
  30778. this._samplingMode = samplingMode;
  30779. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30780. };
  30781. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30782. x *= this.uScale;
  30783. y *= this.vScale;
  30784. x -= this.uRotationCenter * this.uScale;
  30785. y -= this.vRotationCenter * this.vScale;
  30786. z -= this.wRotationCenter;
  30787. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30788. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30789. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30790. t.z += this.wRotationCenter;
  30791. };
  30792. Texture.prototype.getTextureMatrix = function () {
  30793. var _this = this;
  30794. if (this.uOffset === this._cachedUOffset &&
  30795. this.vOffset === this._cachedVOffset &&
  30796. this.uScale === this._cachedUScale &&
  30797. this.vScale === this._cachedVScale &&
  30798. this.uAng === this._cachedUAng &&
  30799. this.vAng === this._cachedVAng &&
  30800. this.wAng === this._cachedWAng) {
  30801. return this._cachedTextureMatrix;
  30802. }
  30803. this._cachedUOffset = this.uOffset;
  30804. this._cachedVOffset = this.vOffset;
  30805. this._cachedUScale = this.uScale;
  30806. this._cachedVScale = this.vScale;
  30807. this._cachedUAng = this.uAng;
  30808. this._cachedVAng = this.vAng;
  30809. this._cachedWAng = this.wAng;
  30810. if (!this._cachedTextureMatrix) {
  30811. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30812. this._rowGenerationMatrix = new BABYLON.Matrix();
  30813. this._t0 = BABYLON.Vector3.Zero();
  30814. this._t1 = BABYLON.Vector3.Zero();
  30815. this._t2 = BABYLON.Vector3.Zero();
  30816. }
  30817. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30818. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30819. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30820. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30821. this._t1.subtractInPlace(this._t0);
  30822. this._t2.subtractInPlace(this._t0);
  30823. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30824. this._cachedTextureMatrix.m[0] = this._t1.x;
  30825. this._cachedTextureMatrix.m[1] = this._t1.y;
  30826. this._cachedTextureMatrix.m[2] = this._t1.z;
  30827. this._cachedTextureMatrix.m[4] = this._t2.x;
  30828. this._cachedTextureMatrix.m[5] = this._t2.y;
  30829. this._cachedTextureMatrix.m[6] = this._t2.z;
  30830. this._cachedTextureMatrix.m[8] = this._t0.x;
  30831. this._cachedTextureMatrix.m[9] = this._t0.y;
  30832. this._cachedTextureMatrix.m[10] = this._t0.z;
  30833. var scene = this.getScene();
  30834. if (!scene) {
  30835. return this._cachedTextureMatrix;
  30836. }
  30837. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30838. return mat.hasTexture(_this);
  30839. });
  30840. return this._cachedTextureMatrix;
  30841. };
  30842. Texture.prototype.getReflectionTextureMatrix = function () {
  30843. var _this = this;
  30844. var scene = this.getScene();
  30845. if (!scene) {
  30846. return this._cachedTextureMatrix;
  30847. }
  30848. if (this.uOffset === this._cachedUOffset &&
  30849. this.vOffset === this._cachedVOffset &&
  30850. this.uScale === this._cachedUScale &&
  30851. this.vScale === this._cachedVScale &&
  30852. this.coordinatesMode === this._cachedCoordinatesMode) {
  30853. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30854. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30855. return this._cachedTextureMatrix;
  30856. }
  30857. }
  30858. else {
  30859. return this._cachedTextureMatrix;
  30860. }
  30861. }
  30862. if (!this._cachedTextureMatrix) {
  30863. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30864. }
  30865. if (!this._projectionModeMatrix) {
  30866. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30867. }
  30868. this._cachedUOffset = this.uOffset;
  30869. this._cachedVOffset = this.vOffset;
  30870. this._cachedUScale = this.uScale;
  30871. this._cachedVScale = this.vScale;
  30872. this._cachedCoordinatesMode = this.coordinatesMode;
  30873. switch (this.coordinatesMode) {
  30874. case Texture.PLANAR_MODE:
  30875. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30876. this._cachedTextureMatrix[0] = this.uScale;
  30877. this._cachedTextureMatrix[5] = this.vScale;
  30878. this._cachedTextureMatrix[12] = this.uOffset;
  30879. this._cachedTextureMatrix[13] = this.vOffset;
  30880. break;
  30881. case Texture.PROJECTION_MODE:
  30882. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30883. this._projectionModeMatrix.m[0] = 0.5;
  30884. this._projectionModeMatrix.m[5] = -0.5;
  30885. this._projectionModeMatrix.m[10] = 0.0;
  30886. this._projectionModeMatrix.m[12] = 0.5;
  30887. this._projectionModeMatrix.m[13] = 0.5;
  30888. this._projectionModeMatrix.m[14] = 1.0;
  30889. this._projectionModeMatrix.m[15] = 1.0;
  30890. var projectionMatrix = scene.getProjectionMatrix();
  30891. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30892. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30893. break;
  30894. default:
  30895. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30896. break;
  30897. }
  30898. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30899. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30900. });
  30901. return this._cachedTextureMatrix;
  30902. };
  30903. Texture.prototype.clone = function () {
  30904. var _this = this;
  30905. return BABYLON.SerializationHelper.Clone(function () {
  30906. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30907. }, this);
  30908. };
  30909. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30910. get: function () {
  30911. if (!this._onLoadObservable) {
  30912. this._onLoadObservable = new BABYLON.Observable();
  30913. }
  30914. return this._onLoadObservable;
  30915. },
  30916. enumerable: true,
  30917. configurable: true
  30918. });
  30919. Texture.prototype.serialize = function () {
  30920. var serializationObject = _super.prototype.serialize.call(this);
  30921. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30922. serializationObject.base64String = this._buffer;
  30923. serializationObject.name = serializationObject.name.replace("data:", "");
  30924. }
  30925. serializationObject.invertY = this._invertY;
  30926. serializationObject.samplingMode = this.samplingMode;
  30927. return serializationObject;
  30928. };
  30929. Texture.prototype.getClassName = function () {
  30930. return "Texture";
  30931. };
  30932. Texture.prototype.dispose = function () {
  30933. _super.prototype.dispose.call(this);
  30934. if (this.onLoadObservable) {
  30935. this.onLoadObservable.clear();
  30936. this._onLoadObservable = null;
  30937. }
  30938. this._delayedOnLoad = null;
  30939. this._delayedOnError = null;
  30940. };
  30941. // Statics
  30942. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30943. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30944. if (onLoad === void 0) { onLoad = null; }
  30945. if (onError === void 0) { onError = null; }
  30946. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30947. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30948. };
  30949. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30950. if (parsedTexture.customType) {
  30951. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30952. // Update Sampling Mode
  30953. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30954. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30955. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30956. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30957. }
  30958. }
  30959. return parsedCustomTexture;
  30960. }
  30961. if (parsedTexture.isCube) {
  30962. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30963. }
  30964. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30965. return null;
  30966. }
  30967. var texture = BABYLON.SerializationHelper.Parse(function () {
  30968. var generateMipMaps = true;
  30969. if (parsedTexture.noMipmap) {
  30970. generateMipMaps = false;
  30971. }
  30972. if (parsedTexture.mirrorPlane) {
  30973. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30974. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30975. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30976. return mirrorTexture;
  30977. }
  30978. else if (parsedTexture.isRenderTarget) {
  30979. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30980. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30981. return renderTargetTexture;
  30982. }
  30983. else {
  30984. var texture;
  30985. if (parsedTexture.base64String) {
  30986. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30987. }
  30988. else {
  30989. var url = rootUrl + parsedTexture.name;
  30990. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30991. url = parsedTexture.url;
  30992. }
  30993. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30994. }
  30995. return texture;
  30996. }
  30997. }, parsedTexture, scene);
  30998. // Update Sampling Mode
  30999. if (parsedTexture.samplingMode) {
  31000. var sampling = parsedTexture.samplingMode;
  31001. if (texture._samplingMode !== sampling) {
  31002. texture.updateSamplingMode(sampling);
  31003. }
  31004. }
  31005. // Animations
  31006. if (parsedTexture.animations) {
  31007. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31008. var parsedAnimation = parsedTexture.animations[animationIndex];
  31009. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31010. }
  31011. }
  31012. return texture;
  31013. };
  31014. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31015. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31016. if (noMipmap === void 0) { noMipmap = false; }
  31017. if (invertY === void 0) { invertY = true; }
  31018. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31019. if (onLoad === void 0) { onLoad = null; }
  31020. if (onError === void 0) { onError = null; }
  31021. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31022. if (name.substr(0, 5) !== "data:") {
  31023. name = "data:" + name;
  31024. }
  31025. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31026. };
  31027. // Constants
  31028. Texture.NEAREST_SAMPLINGMODE = 1;
  31029. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31030. Texture.BILINEAR_SAMPLINGMODE = 2;
  31031. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31032. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31033. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31034. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31035. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31036. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31037. Texture.NEAREST_LINEAR = 7;
  31038. Texture.NEAREST_NEAREST = 8;
  31039. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31040. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31041. Texture.LINEAR_LINEAR = 11;
  31042. Texture.LINEAR_NEAREST = 12;
  31043. Texture.EXPLICIT_MODE = 0;
  31044. Texture.SPHERICAL_MODE = 1;
  31045. Texture.PLANAR_MODE = 2;
  31046. Texture.CUBIC_MODE = 3;
  31047. Texture.PROJECTION_MODE = 4;
  31048. Texture.SKYBOX_MODE = 5;
  31049. Texture.INVCUBIC_MODE = 6;
  31050. Texture.EQUIRECTANGULAR_MODE = 7;
  31051. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31052. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31053. Texture.CLAMP_ADDRESSMODE = 0;
  31054. Texture.WRAP_ADDRESSMODE = 1;
  31055. Texture.MIRROR_ADDRESSMODE = 2;
  31056. /**
  31057. * 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
  31058. */
  31059. Texture.UseSerializedUrlIfAny = false;
  31060. __decorate([
  31061. BABYLON.serialize()
  31062. ], Texture.prototype, "url", void 0);
  31063. __decorate([
  31064. BABYLON.serialize()
  31065. ], Texture.prototype, "uOffset", void 0);
  31066. __decorate([
  31067. BABYLON.serialize()
  31068. ], Texture.prototype, "vOffset", void 0);
  31069. __decorate([
  31070. BABYLON.serialize()
  31071. ], Texture.prototype, "uScale", void 0);
  31072. __decorate([
  31073. BABYLON.serialize()
  31074. ], Texture.prototype, "vScale", void 0);
  31075. __decorate([
  31076. BABYLON.serialize()
  31077. ], Texture.prototype, "uAng", void 0);
  31078. __decorate([
  31079. BABYLON.serialize()
  31080. ], Texture.prototype, "vAng", void 0);
  31081. __decorate([
  31082. BABYLON.serialize()
  31083. ], Texture.prototype, "wAng", void 0);
  31084. __decorate([
  31085. BABYLON.serialize()
  31086. ], Texture.prototype, "uRotationCenter", void 0);
  31087. __decorate([
  31088. BABYLON.serialize()
  31089. ], Texture.prototype, "vRotationCenter", void 0);
  31090. __decorate([
  31091. BABYLON.serialize()
  31092. ], Texture.prototype, "wRotationCenter", void 0);
  31093. __decorate([
  31094. BABYLON.serialize()
  31095. ], Texture.prototype, "isBlocking", null);
  31096. return Texture;
  31097. }(BABYLON.BaseTexture));
  31098. BABYLON.Texture = Texture;
  31099. })(BABYLON || (BABYLON = {}));
  31100. //# sourceMappingURL=babylon.texture.js.map
  31101. var BABYLON;
  31102. (function (BABYLON) {
  31103. /**
  31104. * @hidden
  31105. **/
  31106. var _InstancesBatch = /** @class */ (function () {
  31107. function _InstancesBatch() {
  31108. this.mustReturn = false;
  31109. this.visibleInstances = new Array();
  31110. this.renderSelf = new Array();
  31111. }
  31112. return _InstancesBatch;
  31113. }());
  31114. BABYLON._InstancesBatch = _InstancesBatch;
  31115. var Mesh = /** @class */ (function (_super) {
  31116. __extends(Mesh, _super);
  31117. /**
  31118. * @constructor
  31119. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31120. * @param {Scene} scene The scene to add this mesh to.
  31121. * @param {Node} parent The parent of this mesh, if it has one
  31122. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31123. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31124. * When false, achieved by calling a clone(), also passing False.
  31125. * This will make creation of children, recursive.
  31126. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31127. */
  31128. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31129. if (scene === void 0) { scene = null; }
  31130. if (parent === void 0) { parent = null; }
  31131. if (source === void 0) { source = null; }
  31132. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31133. var _this = _super.call(this, name, scene) || this;
  31134. // Events
  31135. /**
  31136. * An event triggered before rendering the mesh
  31137. */
  31138. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31139. /**
  31140. * An event triggered after rendering the mesh
  31141. */
  31142. _this.onAfterRenderObservable = new BABYLON.Observable();
  31143. /**
  31144. * An event triggered before drawing the mesh
  31145. */
  31146. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31147. // Members
  31148. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31149. _this.instances = new Array();
  31150. _this._LODLevels = new Array();
  31151. _this._visibleInstances = {};
  31152. _this._renderIdForInstances = new Array();
  31153. _this._batchCache = new _InstancesBatch();
  31154. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31155. // Use by builder only to know what orientation were the mesh build in.
  31156. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31157. _this.overrideMaterialSideOrientation = null;
  31158. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31159. // Will be used to save a source mesh reference, If any
  31160. _this._source = null;
  31161. scene = _this.getScene();
  31162. if (source) {
  31163. // Geometry
  31164. if (source._geometry) {
  31165. source._geometry.applyToMesh(_this);
  31166. }
  31167. // Deep copy
  31168. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31169. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31170. // Source mesh
  31171. _this._source = source;
  31172. // Metadata
  31173. if (source.metadata && source.metadata.clone) {
  31174. _this.metadata = source.metadata.clone();
  31175. }
  31176. else {
  31177. _this.metadata = source.metadata;
  31178. }
  31179. // Tags
  31180. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31181. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31182. }
  31183. // Parent
  31184. _this.parent = source.parent;
  31185. // Pivot
  31186. _this.setPivotMatrix(source.getPivotMatrix());
  31187. _this.id = name + "." + source.id;
  31188. // Material
  31189. _this.material = source.material;
  31190. var index;
  31191. if (!doNotCloneChildren) {
  31192. // Children
  31193. var directDescendants = source.getDescendants(true);
  31194. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31195. var child = directDescendants[index_1];
  31196. if (child.clone) {
  31197. child.clone(name + "." + child.name, _this);
  31198. }
  31199. }
  31200. }
  31201. // Physics clone
  31202. var physicsEngine = _this.getScene().getPhysicsEngine();
  31203. if (clonePhysicsImpostor && physicsEngine) {
  31204. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31205. if (impostor) {
  31206. _this.physicsImpostor = impostor.clone(_this);
  31207. }
  31208. }
  31209. // Particles
  31210. for (index = 0; index < scene.particleSystems.length; index++) {
  31211. var system = scene.particleSystems[index];
  31212. if (system.emitter === source) {
  31213. system.clone(system.name, _this);
  31214. }
  31215. }
  31216. _this.computeWorldMatrix(true);
  31217. }
  31218. // Parent
  31219. if (parent !== null) {
  31220. _this.parent = parent;
  31221. }
  31222. return _this;
  31223. }
  31224. Object.defineProperty(Mesh, "FRONTSIDE", {
  31225. /**
  31226. * Mesh side orientation : usually the external or front surface
  31227. */
  31228. get: function () {
  31229. return Mesh._FRONTSIDE;
  31230. },
  31231. enumerable: true,
  31232. configurable: true
  31233. });
  31234. Object.defineProperty(Mesh, "BACKSIDE", {
  31235. /**
  31236. * Mesh side orientation : usually the internal or back surface
  31237. */
  31238. get: function () {
  31239. return Mesh._BACKSIDE;
  31240. },
  31241. enumerable: true,
  31242. configurable: true
  31243. });
  31244. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31245. /**
  31246. * Mesh side orientation : both internal and external or front and back surfaces
  31247. */
  31248. get: function () {
  31249. return Mesh._DOUBLESIDE;
  31250. },
  31251. enumerable: true,
  31252. configurable: true
  31253. });
  31254. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31255. /**
  31256. * Mesh side orientation : by default, `FRONTSIDE`
  31257. */
  31258. get: function () {
  31259. return Mesh._DEFAULTSIDE;
  31260. },
  31261. enumerable: true,
  31262. configurable: true
  31263. });
  31264. Object.defineProperty(Mesh, "NO_CAP", {
  31265. /**
  31266. * Mesh cap setting : no cap
  31267. */
  31268. get: function () {
  31269. return Mesh._NO_CAP;
  31270. },
  31271. enumerable: true,
  31272. configurable: true
  31273. });
  31274. Object.defineProperty(Mesh, "CAP_START", {
  31275. /**
  31276. * Mesh cap setting : one cap at the beginning of the mesh
  31277. */
  31278. get: function () {
  31279. return Mesh._CAP_START;
  31280. },
  31281. enumerable: true,
  31282. configurable: true
  31283. });
  31284. Object.defineProperty(Mesh, "CAP_END", {
  31285. /**
  31286. * Mesh cap setting : one cap at the end of the mesh
  31287. */
  31288. get: function () {
  31289. return Mesh._CAP_END;
  31290. },
  31291. enumerable: true,
  31292. configurable: true
  31293. });
  31294. Object.defineProperty(Mesh, "CAP_ALL", {
  31295. /**
  31296. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31297. */
  31298. get: function () {
  31299. return Mesh._CAP_ALL;
  31300. },
  31301. enumerable: true,
  31302. configurable: true
  31303. });
  31304. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31305. set: function (callback) {
  31306. if (this._onBeforeDrawObserver) {
  31307. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31308. }
  31309. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31310. },
  31311. enumerable: true,
  31312. configurable: true
  31313. });
  31314. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31315. get: function () {
  31316. return this._morphTargetManager;
  31317. },
  31318. set: function (value) {
  31319. if (this._morphTargetManager === value) {
  31320. return;
  31321. }
  31322. this._morphTargetManager = value;
  31323. this._syncGeometryWithMorphTargetManager();
  31324. },
  31325. enumerable: true,
  31326. configurable: true
  31327. });
  31328. Object.defineProperty(Mesh.prototype, "source", {
  31329. get: function () {
  31330. return this._source;
  31331. },
  31332. enumerable: true,
  31333. configurable: true
  31334. });
  31335. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31336. get: function () {
  31337. return this._unIndexed;
  31338. },
  31339. set: function (value) {
  31340. if (this._unIndexed !== value) {
  31341. this._unIndexed = value;
  31342. this._markSubMeshesAsAttributesDirty();
  31343. }
  31344. },
  31345. enumerable: true,
  31346. configurable: true
  31347. });
  31348. // Methods
  31349. /**
  31350. * Returns the string "Mesh".
  31351. */
  31352. Mesh.prototype.getClassName = function () {
  31353. return "Mesh";
  31354. };
  31355. /**
  31356. * Returns a string.
  31357. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31358. */
  31359. Mesh.prototype.toString = function (fullDetails) {
  31360. var ret = _super.prototype.toString.call(this, fullDetails);
  31361. ret += ", n vertices: " + this.getTotalVertices();
  31362. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31363. if (this.animations) {
  31364. for (var i = 0; i < this.animations.length; i++) {
  31365. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31366. }
  31367. }
  31368. if (fullDetails) {
  31369. if (this._geometry) {
  31370. var ib = this.getIndices();
  31371. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31372. if (vb && ib) {
  31373. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31374. }
  31375. }
  31376. else {
  31377. ret += ", flat shading: UNKNOWN";
  31378. }
  31379. }
  31380. return ret;
  31381. };
  31382. Mesh.prototype._unBindEffect = function () {
  31383. _super.prototype._unBindEffect.call(this);
  31384. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31385. var instance = _a[_i];
  31386. instance._unBindEffect();
  31387. }
  31388. };
  31389. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31390. /**
  31391. * True if the mesh has some Levels Of Details (LOD).
  31392. * Returns a boolean.
  31393. */
  31394. get: function () {
  31395. return this._LODLevels.length > 0;
  31396. },
  31397. enumerable: true,
  31398. configurable: true
  31399. });
  31400. /**
  31401. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31402. * @returns an array of {BABYLON.MeshLODLevel}
  31403. */
  31404. Mesh.prototype.getLODLevels = function () {
  31405. return this._LODLevels;
  31406. };
  31407. Mesh.prototype._sortLODLevels = function () {
  31408. this._LODLevels.sort(function (a, b) {
  31409. if (a.distance < b.distance) {
  31410. return 1;
  31411. }
  31412. if (a.distance > b.distance) {
  31413. return -1;
  31414. }
  31415. return 0;
  31416. });
  31417. };
  31418. /**
  31419. * Add a mesh as LOD level triggered at the given distance.
  31420. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31421. * @param {number} distance The distance from the center of the object to show this level
  31422. * @param {Mesh} mesh The mesh to be added as LOD level
  31423. * @return {Mesh} This mesh (for chaining)
  31424. */
  31425. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31426. if (mesh && mesh._masterMesh) {
  31427. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31428. return this;
  31429. }
  31430. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31431. this._LODLevels.push(level);
  31432. if (mesh) {
  31433. mesh._masterMesh = this;
  31434. }
  31435. this._sortLODLevels();
  31436. return this;
  31437. };
  31438. /**
  31439. * Returns the LOD level mesh at the passed distance or null if not found.
  31440. * It is related to the method `addLODLevel(distance, mesh)`.
  31441. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31442. * Returns an object Mesh or `null`.
  31443. */
  31444. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31445. for (var index = 0; index < this._LODLevels.length; index++) {
  31446. var level = this._LODLevels[index];
  31447. if (level.distance === distance) {
  31448. return level.mesh;
  31449. }
  31450. }
  31451. return null;
  31452. };
  31453. /**
  31454. * Remove a mesh from the LOD array
  31455. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31456. * @param {Mesh} mesh The mesh to be removed.
  31457. * @return {Mesh} This mesh (for chaining)
  31458. */
  31459. Mesh.prototype.removeLODLevel = function (mesh) {
  31460. for (var index = 0; index < this._LODLevels.length; index++) {
  31461. if (this._LODLevels[index].mesh === mesh) {
  31462. this._LODLevels.splice(index, 1);
  31463. if (mesh) {
  31464. mesh._masterMesh = null;
  31465. }
  31466. }
  31467. }
  31468. this._sortLODLevels();
  31469. return this;
  31470. };
  31471. /**
  31472. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31473. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31474. */
  31475. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31476. if (!this._LODLevels || this._LODLevels.length === 0) {
  31477. return this;
  31478. }
  31479. var bSphere;
  31480. if (boundingSphere) {
  31481. bSphere = boundingSphere;
  31482. }
  31483. else {
  31484. var boundingInfo = this.getBoundingInfo();
  31485. bSphere = boundingInfo.boundingSphere;
  31486. }
  31487. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31488. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31489. if (this.onLODLevelSelection) {
  31490. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31491. }
  31492. return this;
  31493. }
  31494. for (var index = 0; index < this._LODLevels.length; index++) {
  31495. var level = this._LODLevels[index];
  31496. if (level.distance < distanceToCamera) {
  31497. if (level.mesh) {
  31498. level.mesh._preActivate();
  31499. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31500. }
  31501. if (this.onLODLevelSelection) {
  31502. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31503. }
  31504. return level.mesh;
  31505. }
  31506. }
  31507. if (this.onLODLevelSelection) {
  31508. this.onLODLevelSelection(distanceToCamera, this, this);
  31509. }
  31510. return this;
  31511. };
  31512. Object.defineProperty(Mesh.prototype, "geometry", {
  31513. /**
  31514. * Returns the mesh internal Geometry object.
  31515. */
  31516. get: function () {
  31517. return this._geometry;
  31518. },
  31519. enumerable: true,
  31520. configurable: true
  31521. });
  31522. /**
  31523. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31524. */
  31525. Mesh.prototype.getTotalVertices = function () {
  31526. if (this._geometry === null || this._geometry === undefined) {
  31527. return 0;
  31528. }
  31529. return this._geometry.getTotalVertices();
  31530. };
  31531. /**
  31532. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31533. * 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.
  31534. * You can force the copy with forceCopy === true
  31535. * Returns null if the mesh has no geometry or no vertex buffer.
  31536. * Possible `kind` values :
  31537. * - BABYLON.VertexBuffer.PositionKind
  31538. * - BABYLON.VertexBuffer.UVKind
  31539. * - BABYLON.VertexBuffer.UV2Kind
  31540. * - BABYLON.VertexBuffer.UV3Kind
  31541. * - BABYLON.VertexBuffer.UV4Kind
  31542. * - BABYLON.VertexBuffer.UV5Kind
  31543. * - BABYLON.VertexBuffer.UV6Kind
  31544. * - BABYLON.VertexBuffer.ColorKind
  31545. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31546. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31547. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31548. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31549. */
  31550. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31551. if (!this._geometry) {
  31552. return null;
  31553. }
  31554. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31555. };
  31556. /**
  31557. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31558. * Returns `null` if the mesh has no geometry.
  31559. * Possible `kind` values :
  31560. * - BABYLON.VertexBuffer.PositionKind
  31561. * - BABYLON.VertexBuffer.UVKind
  31562. * - BABYLON.VertexBuffer.UV2Kind
  31563. * - BABYLON.VertexBuffer.UV3Kind
  31564. * - BABYLON.VertexBuffer.UV4Kind
  31565. * - BABYLON.VertexBuffer.UV5Kind
  31566. * - BABYLON.VertexBuffer.UV6Kind
  31567. * - BABYLON.VertexBuffer.ColorKind
  31568. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31569. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31570. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31571. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31572. */
  31573. Mesh.prototype.getVertexBuffer = function (kind) {
  31574. if (!this._geometry) {
  31575. return null;
  31576. }
  31577. return this._geometry.getVertexBuffer(kind);
  31578. };
  31579. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31580. if (!this._geometry) {
  31581. if (this._delayInfo) {
  31582. return this._delayInfo.indexOf(kind) !== -1;
  31583. }
  31584. return false;
  31585. }
  31586. return this._geometry.isVerticesDataPresent(kind);
  31587. };
  31588. /**
  31589. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31590. * Possible `kind` values :
  31591. * - BABYLON.VertexBuffer.PositionKind
  31592. * - BABYLON.VertexBuffer.UVKind
  31593. * - BABYLON.VertexBuffer.UV2Kind
  31594. * - BABYLON.VertexBuffer.UV3Kind
  31595. * - BABYLON.VertexBuffer.UV4Kind
  31596. * - BABYLON.VertexBuffer.UV5Kind
  31597. * - BABYLON.VertexBuffer.UV6Kind
  31598. * - BABYLON.VertexBuffer.ColorKind
  31599. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31600. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31601. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31602. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31603. */
  31604. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31605. if (!this._geometry) {
  31606. if (this._delayInfo) {
  31607. return this._delayInfo.indexOf(kind) !== -1;
  31608. }
  31609. return false;
  31610. }
  31611. return this._geometry.isVertexBufferUpdatable(kind);
  31612. };
  31613. /**
  31614. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31615. * Possible `kind` values :
  31616. * - BABYLON.VertexBuffer.PositionKind
  31617. * - BABYLON.VertexBuffer.UVKind
  31618. * - BABYLON.VertexBuffer.UV2Kind
  31619. * - BABYLON.VertexBuffer.UV3Kind
  31620. * - BABYLON.VertexBuffer.UV4Kind
  31621. * - BABYLON.VertexBuffer.UV5Kind
  31622. * - BABYLON.VertexBuffer.UV6Kind
  31623. * - BABYLON.VertexBuffer.ColorKind
  31624. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31625. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31626. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31627. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31628. */
  31629. Mesh.prototype.getVerticesDataKinds = function () {
  31630. if (!this._geometry) {
  31631. var result = new Array();
  31632. if (this._delayInfo) {
  31633. this._delayInfo.forEach(function (kind, index, array) {
  31634. result.push(kind);
  31635. });
  31636. }
  31637. return result;
  31638. }
  31639. return this._geometry.getVerticesDataKinds();
  31640. };
  31641. /**
  31642. * Returns a positive integer : the total number of indices in this mesh geometry.
  31643. * Returns zero if the mesh has no geometry.
  31644. */
  31645. Mesh.prototype.getTotalIndices = function () {
  31646. if (!this._geometry) {
  31647. return 0;
  31648. }
  31649. return this._geometry.getTotalIndices();
  31650. };
  31651. /**
  31652. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31653. * 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.
  31654. * Returns an empty array if the mesh has no geometry.
  31655. */
  31656. Mesh.prototype.getIndices = function (copyWhenShared) {
  31657. if (!this._geometry) {
  31658. return [];
  31659. }
  31660. return this._geometry.getIndices(copyWhenShared);
  31661. };
  31662. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31663. get: function () {
  31664. return this._masterMesh !== null && this._masterMesh !== undefined;
  31665. },
  31666. enumerable: true,
  31667. configurable: true
  31668. });
  31669. /**
  31670. * Determine if the current mesh is ready to be rendered
  31671. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31672. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31673. * @returns true if all associated assets are ready (material, textures, shaders)
  31674. */
  31675. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31676. if (completeCheck === void 0) { completeCheck = false; }
  31677. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31678. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31679. return false;
  31680. }
  31681. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31682. return false;
  31683. }
  31684. if (!this.subMeshes || this.subMeshes.length === 0) {
  31685. return true;
  31686. }
  31687. if (!completeCheck) {
  31688. return true;
  31689. }
  31690. var engine = this.getEngine();
  31691. var scene = this.getScene();
  31692. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31693. this.computeWorldMatrix();
  31694. var mat = this.material || scene.defaultMaterial;
  31695. if (mat) {
  31696. if (mat.storeEffectOnSubMeshes) {
  31697. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31698. var subMesh = _a[_i];
  31699. var effectiveMaterial = subMesh.getMaterial();
  31700. if (effectiveMaterial) {
  31701. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31702. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31703. return false;
  31704. }
  31705. }
  31706. else {
  31707. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31708. return false;
  31709. }
  31710. }
  31711. }
  31712. }
  31713. }
  31714. else {
  31715. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31716. return false;
  31717. }
  31718. }
  31719. }
  31720. // Shadows
  31721. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31722. var light = _c[_b];
  31723. var generator = light.getShadowGenerator();
  31724. if (generator) {
  31725. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31726. var subMesh = _e[_d];
  31727. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31728. return false;
  31729. }
  31730. }
  31731. }
  31732. }
  31733. // LOD
  31734. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31735. var lod = _g[_f];
  31736. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31737. return false;
  31738. }
  31739. }
  31740. return true;
  31741. };
  31742. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31743. /**
  31744. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31745. * This property is pertinent only for updatable parametric shapes.
  31746. */
  31747. get: function () {
  31748. return this._areNormalsFrozen;
  31749. },
  31750. enumerable: true,
  31751. configurable: true
  31752. });
  31753. /**
  31754. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31755. * It has no effect at all on other shapes.
  31756. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31757. * Returns the Mesh.
  31758. */
  31759. Mesh.prototype.freezeNormals = function () {
  31760. this._areNormalsFrozen = true;
  31761. return this;
  31762. };
  31763. /**
  31764. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31765. * It has no effect at all on other shapes.
  31766. * It reactivates the mesh normals computation if it was previously frozen.
  31767. * Returns the Mesh.
  31768. */
  31769. Mesh.prototype.unfreezeNormals = function () {
  31770. this._areNormalsFrozen = false;
  31771. return this;
  31772. };
  31773. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31774. /**
  31775. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31776. */
  31777. set: function (count) {
  31778. this._overridenInstanceCount = count;
  31779. },
  31780. enumerable: true,
  31781. configurable: true
  31782. });
  31783. // Methods
  31784. Mesh.prototype._preActivate = function () {
  31785. var sceneRenderId = this.getScene().getRenderId();
  31786. if (this._preActivateId === sceneRenderId) {
  31787. return this;
  31788. }
  31789. this._preActivateId = sceneRenderId;
  31790. this._visibleInstances = null;
  31791. return this;
  31792. };
  31793. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31794. if (this._visibleInstances) {
  31795. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31796. }
  31797. return this;
  31798. };
  31799. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31800. if (!this._visibleInstances) {
  31801. this._visibleInstances = {};
  31802. this._visibleInstances.defaultRenderId = renderId;
  31803. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31804. }
  31805. if (!this._visibleInstances[renderId]) {
  31806. this._visibleInstances[renderId] = new Array();
  31807. }
  31808. this._visibleInstances[renderId].push(instance);
  31809. return this;
  31810. };
  31811. /**
  31812. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31813. * This means the mesh underlying bounding box and sphere are recomputed.
  31814. * Returns the Mesh.
  31815. */
  31816. Mesh.prototype.refreshBoundingInfo = function () {
  31817. return this._refreshBoundingInfo(false);
  31818. };
  31819. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31820. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31821. return this;
  31822. }
  31823. var data = this._getPositionData(applySkeleton);
  31824. if (data) {
  31825. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31826. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31827. }
  31828. if (this.subMeshes) {
  31829. for (var index = 0; index < this.subMeshes.length; index++) {
  31830. this.subMeshes[index].refreshBoundingInfo();
  31831. }
  31832. }
  31833. this._updateBoundingInfo();
  31834. return this;
  31835. };
  31836. Mesh.prototype._getPositionData = function (applySkeleton) {
  31837. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31838. if (data && applySkeleton && this.skeleton) {
  31839. data = BABYLON.Tools.Slice(data);
  31840. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31841. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31842. if (matricesWeightsData && matricesIndicesData) {
  31843. var needExtras = this.numBoneInfluencers > 4;
  31844. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31845. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31846. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31847. var tempVector = BABYLON.Tmp.Vector3[0];
  31848. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31849. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31850. var matWeightIdx = 0;
  31851. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31852. finalMatrix.reset();
  31853. var inf;
  31854. var weight;
  31855. for (inf = 0; inf < 4; inf++) {
  31856. weight = matricesWeightsData[matWeightIdx + inf];
  31857. if (weight <= 0)
  31858. break;
  31859. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31860. finalMatrix.addToSelf(tempMatrix);
  31861. }
  31862. if (needExtras) {
  31863. for (inf = 0; inf < 4; inf++) {
  31864. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31865. if (weight <= 0)
  31866. break;
  31867. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31868. finalMatrix.addToSelf(tempMatrix);
  31869. }
  31870. }
  31871. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31872. tempVector.toArray(data, index);
  31873. }
  31874. }
  31875. }
  31876. return data;
  31877. };
  31878. Mesh.prototype._createGlobalSubMesh = function (force) {
  31879. var totalVertices = this.getTotalVertices();
  31880. if (!totalVertices || !this.getIndices()) {
  31881. return null;
  31882. }
  31883. // Check if we need to recreate the submeshes
  31884. if (this.subMeshes && this.subMeshes.length > 0) {
  31885. var ib = this.getIndices();
  31886. if (!ib) {
  31887. return null;
  31888. }
  31889. var totalIndices = ib.length;
  31890. var needToRecreate = false;
  31891. if (force) {
  31892. needToRecreate = true;
  31893. }
  31894. else {
  31895. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31896. var submesh = _a[_i];
  31897. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31898. needToRecreate = true;
  31899. break;
  31900. }
  31901. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31902. needToRecreate = true;
  31903. break;
  31904. }
  31905. }
  31906. }
  31907. if (!needToRecreate) {
  31908. return this.subMeshes[0];
  31909. }
  31910. }
  31911. this.releaseSubMeshes();
  31912. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31913. };
  31914. Mesh.prototype.subdivide = function (count) {
  31915. if (count < 1) {
  31916. return;
  31917. }
  31918. var totalIndices = this.getTotalIndices();
  31919. var subdivisionSize = (totalIndices / count) | 0;
  31920. var offset = 0;
  31921. // Ensure that subdivisionSize is a multiple of 3
  31922. while (subdivisionSize % 3 !== 0) {
  31923. subdivisionSize++;
  31924. }
  31925. this.releaseSubMeshes();
  31926. for (var index = 0; index < count; index++) {
  31927. if (offset >= totalIndices) {
  31928. break;
  31929. }
  31930. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31931. offset += subdivisionSize;
  31932. }
  31933. this.synchronizeInstances();
  31934. };
  31935. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31936. if (updatable === void 0) { updatable = false; }
  31937. if (!this._geometry) {
  31938. var vertexData = new BABYLON.VertexData();
  31939. vertexData.set(data, kind);
  31940. var scene = this.getScene();
  31941. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31942. }
  31943. else {
  31944. this._geometry.setVerticesData(kind, data, updatable, stride);
  31945. }
  31946. return this;
  31947. };
  31948. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31949. if (updatable === void 0) { updatable = true; }
  31950. var vb = this.getVertexBuffer(kind);
  31951. if (!vb || vb.isUpdatable() === updatable) {
  31952. return;
  31953. }
  31954. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31955. };
  31956. /**
  31957. * Sets the mesh VertexBuffer.
  31958. * Returns the Mesh.
  31959. */
  31960. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31961. if (!this._geometry) {
  31962. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31963. }
  31964. this._geometry.setVerticesBuffer(buffer);
  31965. return this;
  31966. };
  31967. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31968. if (!this._geometry) {
  31969. return this;
  31970. }
  31971. if (!makeItUnique) {
  31972. this._geometry.updateVerticesData(kind, data, updateExtends);
  31973. }
  31974. else {
  31975. this.makeGeometryUnique();
  31976. this.updateVerticesData(kind, data, updateExtends, false);
  31977. }
  31978. return this;
  31979. };
  31980. /**
  31981. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31982. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31983. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31984. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31985. * Returns the Mesh.
  31986. */
  31987. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31988. if (computeNormals === void 0) { computeNormals = true; }
  31989. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31990. if (!positions) {
  31991. return this;
  31992. }
  31993. positionFunction(positions);
  31994. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31995. if (computeNormals) {
  31996. var indices = this.getIndices();
  31997. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31998. if (!normals) {
  31999. return this;
  32000. }
  32001. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32002. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32003. }
  32004. return this;
  32005. };
  32006. /**
  32007. * Creates a un-shared specific occurence of the geometry for the mesh.
  32008. * Returns the Mesh.
  32009. */
  32010. Mesh.prototype.makeGeometryUnique = function () {
  32011. if (!this._geometry) {
  32012. return this;
  32013. }
  32014. var oldGeometry = this._geometry;
  32015. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32016. oldGeometry.releaseForMesh(this, true);
  32017. geometry.applyToMesh(this);
  32018. return this;
  32019. };
  32020. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32021. if (totalVertices === void 0) { totalVertices = null; }
  32022. if (updatable === void 0) { updatable = false; }
  32023. if (!this._geometry) {
  32024. var vertexData = new BABYLON.VertexData();
  32025. vertexData.indices = indices;
  32026. var scene = this.getScene();
  32027. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32028. }
  32029. else {
  32030. this._geometry.setIndices(indices, totalVertices, updatable);
  32031. }
  32032. return this;
  32033. };
  32034. /**
  32035. * Update the current index buffer
  32036. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32037. * Returns the Mesh.
  32038. */
  32039. Mesh.prototype.updateIndices = function (indices, offset) {
  32040. if (!this._geometry) {
  32041. return this;
  32042. }
  32043. this._geometry.updateIndices(indices, offset);
  32044. return this;
  32045. };
  32046. /**
  32047. * Invert the geometry to move from a right handed system to a left handed one.
  32048. * Returns the Mesh.
  32049. */
  32050. Mesh.prototype.toLeftHanded = function () {
  32051. if (!this._geometry) {
  32052. return this;
  32053. }
  32054. this._geometry.toLeftHanded();
  32055. return this;
  32056. };
  32057. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32058. if (!this._geometry) {
  32059. return this;
  32060. }
  32061. var engine = this.getScene().getEngine();
  32062. // Wireframe
  32063. var indexToBind;
  32064. if (this._unIndexed) {
  32065. indexToBind = null;
  32066. }
  32067. else {
  32068. switch (fillMode) {
  32069. case BABYLON.Material.PointFillMode:
  32070. indexToBind = null;
  32071. break;
  32072. case BABYLON.Material.WireFrameFillMode:
  32073. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32074. break;
  32075. default:
  32076. case BABYLON.Material.TriangleFillMode:
  32077. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32078. break;
  32079. }
  32080. }
  32081. // VBOs
  32082. this._geometry._bind(effect, indexToBind);
  32083. return this;
  32084. };
  32085. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32086. if (alternate === void 0) { alternate = false; }
  32087. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32088. return this;
  32089. }
  32090. this.onBeforeDrawObservable.notifyObservers(this);
  32091. var scene = this.getScene();
  32092. var engine = scene.getEngine();
  32093. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32094. // or triangles as points
  32095. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32096. }
  32097. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32098. // Triangles as wireframe
  32099. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32100. }
  32101. else {
  32102. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32103. }
  32104. if (scene._isAlternateRenderingEnabled && !alternate) {
  32105. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32106. if (!effect || !scene.activeCamera) {
  32107. return this;
  32108. }
  32109. scene._switchToAlternateCameraConfiguration(true);
  32110. this._effectiveMaterial.bindView(effect);
  32111. this._effectiveMaterial.bindViewProjection(effect);
  32112. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32113. this._draw(subMesh, fillMode, instancesCount, true);
  32114. engine.setViewport(scene.activeCamera.viewport);
  32115. scene._switchToAlternateCameraConfiguration(false);
  32116. this._effectiveMaterial.bindView(effect);
  32117. this._effectiveMaterial.bindViewProjection(effect);
  32118. }
  32119. return this;
  32120. };
  32121. /**
  32122. * Registers for this mesh a javascript function called just before the rendering process.
  32123. * This function is passed the current mesh.
  32124. * Return the Mesh.
  32125. */
  32126. Mesh.prototype.registerBeforeRender = function (func) {
  32127. this.onBeforeRenderObservable.add(func);
  32128. return this;
  32129. };
  32130. /**
  32131. * Disposes a previously registered javascript function called before the rendering.
  32132. * This function is passed the current mesh.
  32133. * Returns the Mesh.
  32134. */
  32135. Mesh.prototype.unregisterBeforeRender = function (func) {
  32136. this.onBeforeRenderObservable.removeCallback(func);
  32137. return this;
  32138. };
  32139. /**
  32140. * Registers for this mesh a javascript function called just after the rendering is complete.
  32141. * This function is passed the current mesh.
  32142. * Returns the Mesh.
  32143. */
  32144. Mesh.prototype.registerAfterRender = function (func) {
  32145. this.onAfterRenderObservable.add(func);
  32146. return this;
  32147. };
  32148. /**
  32149. * Disposes a previously registered javascript function called after the rendering.
  32150. * This function is passed the current mesh.
  32151. * Return the Mesh.
  32152. */
  32153. Mesh.prototype.unregisterAfterRender = function (func) {
  32154. this.onAfterRenderObservable.removeCallback(func);
  32155. return this;
  32156. };
  32157. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32158. var scene = this.getScene();
  32159. this._batchCache.mustReturn = false;
  32160. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32161. this._batchCache.visibleInstances[subMeshId] = null;
  32162. if (this._visibleInstances) {
  32163. var currentRenderId = scene.getRenderId();
  32164. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32165. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32166. var selfRenderId = this._renderId;
  32167. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32168. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32169. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32170. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32171. }
  32172. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32173. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32174. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32175. this._batchCache.mustReturn = true;
  32176. return this._batchCache;
  32177. }
  32178. if (currentRenderId !== selfRenderId) {
  32179. this._batchCache.renderSelf[subMeshId] = false;
  32180. }
  32181. }
  32182. this._renderIdForInstances[subMeshId] = currentRenderId;
  32183. }
  32184. return this._batchCache;
  32185. };
  32186. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32187. var visibleInstances = batch.visibleInstances[subMesh._id];
  32188. if (!visibleInstances) {
  32189. return this;
  32190. }
  32191. var matricesCount = visibleInstances.length + 1;
  32192. var bufferSize = matricesCount * 16 * 4;
  32193. var currentInstancesBufferSize = this._instancesBufferSize;
  32194. var instancesBuffer = this._instancesBuffer;
  32195. while (this._instancesBufferSize < bufferSize) {
  32196. this._instancesBufferSize *= 2;
  32197. }
  32198. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32199. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32200. }
  32201. var offset = 0;
  32202. var instancesCount = 0;
  32203. var world = this.getWorldMatrix();
  32204. if (batch.renderSelf[subMesh._id]) {
  32205. world.copyToArray(this._instancesData, offset);
  32206. offset += 16;
  32207. instancesCount++;
  32208. }
  32209. if (visibleInstances) {
  32210. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32211. var instance = visibleInstances[instanceIndex];
  32212. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32213. offset += 16;
  32214. instancesCount++;
  32215. }
  32216. }
  32217. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32218. if (instancesBuffer) {
  32219. instancesBuffer.dispose();
  32220. }
  32221. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32222. this._instancesBuffer = instancesBuffer;
  32223. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32224. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32225. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32226. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32227. }
  32228. else {
  32229. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32230. }
  32231. this._bind(subMesh, effect, fillMode);
  32232. this._draw(subMesh, fillMode, instancesCount);
  32233. engine.unbindInstanceAttributes();
  32234. return this;
  32235. };
  32236. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32237. var scene = this.getScene();
  32238. var engine = scene.getEngine();
  32239. if (hardwareInstancedRendering) {
  32240. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32241. }
  32242. else {
  32243. if (batch.renderSelf[subMesh._id]) {
  32244. // Draw
  32245. if (onBeforeDraw) {
  32246. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32247. }
  32248. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32249. }
  32250. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32251. if (visibleInstancesForSubMesh) {
  32252. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32253. var instance = visibleInstancesForSubMesh[instanceIndex];
  32254. // World
  32255. var world = instance.getWorldMatrix();
  32256. if (onBeforeDraw) {
  32257. onBeforeDraw(true, world, effectiveMaterial);
  32258. }
  32259. // Draw
  32260. this._draw(subMesh, fillMode);
  32261. }
  32262. }
  32263. }
  32264. return this;
  32265. };
  32266. /**
  32267. * Triggers the draw call for the mesh.
  32268. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32269. * Returns the Mesh.
  32270. */
  32271. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32272. this._checkOcclusionQuery();
  32273. if (this._isOccluded) {
  32274. return this;
  32275. }
  32276. var scene = this.getScene();
  32277. // Managing instances
  32278. var batch = this._getInstancesRenderList(subMesh._id);
  32279. if (batch.mustReturn) {
  32280. return this;
  32281. }
  32282. // Checking geometry state
  32283. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32284. return this;
  32285. }
  32286. this.onBeforeRenderObservable.notifyObservers(this);
  32287. var engine = scene.getEngine();
  32288. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32289. // Material
  32290. var material = subMesh.getMaterial();
  32291. if (!material) {
  32292. return this;
  32293. }
  32294. this._effectiveMaterial = material;
  32295. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32296. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32297. return this;
  32298. }
  32299. }
  32300. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32301. return this;
  32302. }
  32303. // Alpha mode
  32304. if (enableAlphaMode) {
  32305. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32306. }
  32307. // Outline - step 1
  32308. var savedDepthWrite = engine.getDepthWrite();
  32309. if (this.renderOutline) {
  32310. engine.setDepthWrite(false);
  32311. scene.getOutlineRenderer().render(subMesh, batch);
  32312. engine.setDepthWrite(savedDepthWrite);
  32313. }
  32314. var effect;
  32315. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32316. effect = subMesh.effect;
  32317. }
  32318. else {
  32319. effect = this._effectiveMaterial.getEffect();
  32320. }
  32321. if (!effect) {
  32322. return this;
  32323. }
  32324. var sideOrientation = this.overrideMaterialSideOrientation;
  32325. if (sideOrientation == null) {
  32326. sideOrientation = this._effectiveMaterial.sideOrientation;
  32327. if (this._getWorldMatrixDeterminant() < 0) {
  32328. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32329. }
  32330. }
  32331. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32332. if (this._effectiveMaterial.forceDepthWrite) {
  32333. engine.setDepthWrite(true);
  32334. }
  32335. // Bind
  32336. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32337. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32338. this._bind(subMesh, effect, fillMode);
  32339. }
  32340. var world = this.getWorldMatrix();
  32341. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32342. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32343. }
  32344. else {
  32345. this._effectiveMaterial.bind(world, this);
  32346. }
  32347. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32348. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32349. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32350. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32351. }
  32352. // Draw
  32353. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32354. // Unbind
  32355. this._effectiveMaterial.unbind();
  32356. // Outline - step 2
  32357. if (this.renderOutline && savedDepthWrite) {
  32358. engine.setDepthWrite(true);
  32359. engine.setColorWrite(false);
  32360. scene.getOutlineRenderer().render(subMesh, batch);
  32361. engine.setColorWrite(true);
  32362. }
  32363. // Overlay
  32364. if (this.renderOverlay) {
  32365. var currentMode = engine.getAlphaMode();
  32366. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32367. scene.getOutlineRenderer().render(subMesh, batch, true);
  32368. engine.setAlphaMode(currentMode);
  32369. }
  32370. this.onAfterRenderObservable.notifyObservers(this);
  32371. return this;
  32372. };
  32373. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32374. if (isInstance && effectiveMaterial) {
  32375. effectiveMaterial.bindOnlyWorldMatrix(world);
  32376. }
  32377. };
  32378. /**
  32379. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32380. */
  32381. Mesh.prototype.getEmittedParticleSystems = function () {
  32382. var results = new Array();
  32383. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32384. var particleSystem = this.getScene().particleSystems[index];
  32385. if (particleSystem.emitter === this) {
  32386. results.push(particleSystem);
  32387. }
  32388. }
  32389. return results;
  32390. };
  32391. /**
  32392. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32393. */
  32394. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32395. var results = new Array();
  32396. var descendants = this.getDescendants();
  32397. descendants.push(this);
  32398. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32399. var particleSystem = this.getScene().particleSystems[index];
  32400. var emitter = particleSystem.emitter;
  32401. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32402. results.push(particleSystem);
  32403. }
  32404. }
  32405. return results;
  32406. };
  32407. /**
  32408. * Normalize matrix weights so that all vertices have a total weight set to 1
  32409. */
  32410. Mesh.prototype.cleanMatrixWeights = function () {
  32411. var epsilon = 1e-3;
  32412. var noInfluenceBoneIndex = 0.0;
  32413. if (this.skeleton) {
  32414. noInfluenceBoneIndex = this.skeleton.bones.length;
  32415. }
  32416. else {
  32417. return;
  32418. }
  32419. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32420. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32421. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32422. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32423. var influencers = this.numBoneInfluencers;
  32424. var size = matricesWeights.length;
  32425. for (var i = 0; i < size; i += 4) {
  32426. var weight = 0.0;
  32427. var firstZeroWeight = -1;
  32428. for (var j = 0; j < 4; j++) {
  32429. var w = matricesWeights[i + j];
  32430. weight += w;
  32431. if (w < epsilon && firstZeroWeight < 0) {
  32432. firstZeroWeight = j;
  32433. }
  32434. }
  32435. if (matricesWeightsExtra) {
  32436. for (var j = 0; j < 4; j++) {
  32437. var w = matricesWeightsExtra[i + j];
  32438. weight += w;
  32439. if (w < epsilon && firstZeroWeight < 0) {
  32440. firstZeroWeight = j + 4;
  32441. }
  32442. }
  32443. }
  32444. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32445. firstZeroWeight = influencers - 1;
  32446. }
  32447. if (weight > epsilon) {
  32448. var mweight = 1.0 / weight;
  32449. for (var j = 0; j < 4; j++) {
  32450. matricesWeights[i + j] *= mweight;
  32451. }
  32452. if (matricesWeightsExtra) {
  32453. for (var j = 0; j < 4; j++) {
  32454. matricesWeightsExtra[i + j] *= mweight;
  32455. }
  32456. }
  32457. }
  32458. else {
  32459. if (firstZeroWeight >= 4) {
  32460. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32461. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32462. }
  32463. else {
  32464. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32465. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32466. }
  32467. }
  32468. }
  32469. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32470. if (matricesIndicesExtra) {
  32471. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32472. }
  32473. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32474. if (matricesWeightsExtra) {
  32475. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32476. }
  32477. };
  32478. Mesh.prototype._checkDelayState = function () {
  32479. var scene = this.getScene();
  32480. if (this._geometry) {
  32481. this._geometry.load(scene);
  32482. }
  32483. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32484. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32485. this._queueLoad(scene);
  32486. }
  32487. return this;
  32488. };
  32489. Mesh.prototype._queueLoad = function (scene) {
  32490. var _this = this;
  32491. scene._addPendingData(this);
  32492. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32493. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32494. if (data instanceof ArrayBuffer) {
  32495. _this._delayLoadingFunction(data, _this);
  32496. }
  32497. else {
  32498. _this._delayLoadingFunction(JSON.parse(data), _this);
  32499. }
  32500. _this.instances.forEach(function (instance) {
  32501. instance._syncSubMeshes();
  32502. });
  32503. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32504. scene._removePendingData(_this);
  32505. }, function () { }, scene.database, getBinaryData);
  32506. return this;
  32507. };
  32508. /**
  32509. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32510. */
  32511. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32512. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32513. return false;
  32514. }
  32515. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32516. return false;
  32517. }
  32518. this._checkDelayState();
  32519. return true;
  32520. };
  32521. /**
  32522. * Sets the mesh material by the material or multiMaterial `id` property.
  32523. * The material `id` is a string identifying the material or the multiMaterial.
  32524. * This method returns the Mesh.
  32525. */
  32526. Mesh.prototype.setMaterialByID = function (id) {
  32527. var materials = this.getScene().materials;
  32528. var index;
  32529. for (index = materials.length - 1; index > -1; index--) {
  32530. if (materials[index].id === id) {
  32531. this.material = materials[index];
  32532. return this;
  32533. }
  32534. }
  32535. // Multi
  32536. var multiMaterials = this.getScene().multiMaterials;
  32537. for (index = multiMaterials.length - 1; index > -1; index--) {
  32538. if (multiMaterials[index].id === id) {
  32539. this.material = multiMaterials[index];
  32540. return this;
  32541. }
  32542. }
  32543. return this;
  32544. };
  32545. /**
  32546. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32547. */
  32548. Mesh.prototype.getAnimatables = function () {
  32549. var results = new Array();
  32550. if (this.material) {
  32551. results.push(this.material);
  32552. }
  32553. if (this.skeleton) {
  32554. results.push(this.skeleton);
  32555. }
  32556. return results;
  32557. };
  32558. /**
  32559. * Modifies the mesh geometry according to the passed transformation matrix.
  32560. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32561. * The mesh normals are modified accordingly the same transformation.
  32562. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32563. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32564. * Returns the Mesh.
  32565. */
  32566. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32567. // Position
  32568. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32569. return this;
  32570. }
  32571. var submeshes = this.subMeshes.splice(0);
  32572. this._resetPointsArrayCache();
  32573. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32574. var temp = new Array();
  32575. var index;
  32576. for (index = 0; index < data.length; index += 3) {
  32577. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32578. }
  32579. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32580. // Normals
  32581. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32582. return this;
  32583. }
  32584. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32585. temp = [];
  32586. for (index = 0; index < data.length; index += 3) {
  32587. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32588. }
  32589. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32590. // flip faces?
  32591. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32592. this.flipFaces();
  32593. }
  32594. // Restore submeshes
  32595. this.releaseSubMeshes();
  32596. this.subMeshes = submeshes;
  32597. return this;
  32598. };
  32599. /**
  32600. * Modifies the mesh geometry according to its own current World Matrix.
  32601. * The mesh World Matrix is then reset.
  32602. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32603. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32604. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32605. * Returns the Mesh.
  32606. */
  32607. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32608. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32609. this.scaling.copyFromFloats(1, 1, 1);
  32610. this.position.copyFromFloats(0, 0, 0);
  32611. this.rotation.copyFromFloats(0, 0, 0);
  32612. //only if quaternion is already set
  32613. if (this.rotationQuaternion) {
  32614. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32615. }
  32616. this._worldMatrix = BABYLON.Matrix.Identity();
  32617. return this;
  32618. };
  32619. Object.defineProperty(Mesh.prototype, "_positions", {
  32620. // Cache
  32621. get: function () {
  32622. if (this._geometry) {
  32623. return this._geometry._positions;
  32624. }
  32625. return null;
  32626. },
  32627. enumerable: true,
  32628. configurable: true
  32629. });
  32630. Mesh.prototype._resetPointsArrayCache = function () {
  32631. if (this._geometry) {
  32632. this._geometry._resetPointsArrayCache();
  32633. }
  32634. return this;
  32635. };
  32636. Mesh.prototype._generatePointsArray = function () {
  32637. if (this._geometry) {
  32638. return this._geometry._generatePointsArray();
  32639. }
  32640. return false;
  32641. };
  32642. /**
  32643. * Returns a new Mesh object generated from the current mesh properties.
  32644. * This method must not get confused with createInstance().
  32645. * The parameter `name` is a string, the name given to the new mesh.
  32646. * The optional parameter `newParent` can be any Node object (default `null`).
  32647. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32648. * 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.
  32649. */
  32650. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32651. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32652. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32653. };
  32654. /**
  32655. * Releases resources associated with this mesh.
  32656. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32657. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32658. */
  32659. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32660. var _this = this;
  32661. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32662. this.morphTargetManager = null;
  32663. if (this._geometry) {
  32664. this._geometry.releaseForMesh(this, true);
  32665. }
  32666. // Sources
  32667. var meshes = this.getScene().meshes;
  32668. meshes.forEach(function (abstractMesh) {
  32669. var mesh = abstractMesh;
  32670. if (mesh._source && mesh._source === _this) {
  32671. mesh._source = null;
  32672. }
  32673. });
  32674. this._source = null;
  32675. // Instances
  32676. if (this._instancesBuffer) {
  32677. this._instancesBuffer.dispose();
  32678. this._instancesBuffer = null;
  32679. }
  32680. while (this.instances.length) {
  32681. this.instances[0].dispose();
  32682. }
  32683. // Effect layers.
  32684. var effectLayers = this.getScene().effectLayers;
  32685. for (var i = 0; i < effectLayers.length; i++) {
  32686. var effectLayer = effectLayers[i];
  32687. if (effectLayer) {
  32688. effectLayer._disposeMesh(this);
  32689. }
  32690. }
  32691. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32692. };
  32693. /**
  32694. * Modifies the mesh geometry according to a displacement map.
  32695. * 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.
  32696. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32697. * This method returns nothing.
  32698. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32699. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32700. * 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.
  32701. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32702. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32703. *
  32704. * Returns the Mesh.
  32705. */
  32706. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32707. var _this = this;
  32708. var scene = this.getScene();
  32709. var onload = function (img) {
  32710. // Getting height map data
  32711. var canvas = document.createElement("canvas");
  32712. var context = canvas.getContext("2d");
  32713. var heightMapWidth = img.width;
  32714. var heightMapHeight = img.height;
  32715. canvas.width = heightMapWidth;
  32716. canvas.height = heightMapHeight;
  32717. context.drawImage(img, 0, 0);
  32718. // Create VertexData from map data
  32719. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32720. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32721. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32722. //execute success callback, if set
  32723. if (onSuccess) {
  32724. onSuccess(_this);
  32725. }
  32726. };
  32727. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32728. return this;
  32729. };
  32730. /**
  32731. * Modifies the mesh geometry according to a displacementMap buffer.
  32732. * 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.
  32733. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32734. * This method returns nothing.
  32735. * 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.
  32736. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32737. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32738. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32739. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32740. *
  32741. * Returns the Mesh.
  32742. */
  32743. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32744. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32745. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32746. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32747. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32748. return this;
  32749. }
  32750. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32751. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32752. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32753. var position = BABYLON.Vector3.Zero();
  32754. var normal = BABYLON.Vector3.Zero();
  32755. var uv = BABYLON.Vector2.Zero();
  32756. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32757. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32758. for (var index = 0; index < positions.length; index += 3) {
  32759. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32760. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32761. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32762. // Compute height
  32763. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32764. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32765. var pos = (u + v * heightMapWidth) * 4;
  32766. var r = buffer[pos] / 255.0;
  32767. var g = buffer[pos + 1] / 255.0;
  32768. var b = buffer[pos + 2] / 255.0;
  32769. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32770. normal.normalize();
  32771. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32772. position = position.add(normal);
  32773. position.toArray(positions, index);
  32774. }
  32775. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32776. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32777. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32778. return this;
  32779. };
  32780. /**
  32781. * Modify the mesh to get a flat shading rendering.
  32782. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32783. * This method returns the Mesh.
  32784. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32785. */
  32786. Mesh.prototype.convertToFlatShadedMesh = function () {
  32787. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32788. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32789. var kinds = this.getVerticesDataKinds();
  32790. var vbs = {};
  32791. var data = {};
  32792. var newdata = {};
  32793. var updatableNormals = false;
  32794. var kindIndex;
  32795. var kind;
  32796. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32797. kind = kinds[kindIndex];
  32798. var vertexBuffer = this.getVertexBuffer(kind);
  32799. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32800. updatableNormals = vertexBuffer.isUpdatable();
  32801. kinds.splice(kindIndex, 1);
  32802. kindIndex--;
  32803. continue;
  32804. }
  32805. vbs[kind] = vertexBuffer;
  32806. data[kind] = vbs[kind].getData();
  32807. newdata[kind] = [];
  32808. }
  32809. // Save previous submeshes
  32810. var previousSubmeshes = this.subMeshes.slice(0);
  32811. var indices = this.getIndices();
  32812. var totalIndices = this.getTotalIndices();
  32813. // Generating unique vertices per face
  32814. var index;
  32815. for (index = 0; index < totalIndices; index++) {
  32816. var vertexIndex = indices[index];
  32817. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32818. kind = kinds[kindIndex];
  32819. var stride = vbs[kind].getStrideSize();
  32820. for (var offset = 0; offset < stride; offset++) {
  32821. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32822. }
  32823. }
  32824. }
  32825. // Updating faces & normal
  32826. var normals = [];
  32827. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32828. for (index = 0; index < totalIndices; index += 3) {
  32829. indices[index] = index;
  32830. indices[index + 1] = index + 1;
  32831. indices[index + 2] = index + 2;
  32832. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32833. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32834. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32835. var p1p2 = p1.subtract(p2);
  32836. var p3p2 = p3.subtract(p2);
  32837. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32838. // Store same normals for every vertex
  32839. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32840. normals.push(normal.x);
  32841. normals.push(normal.y);
  32842. normals.push(normal.z);
  32843. }
  32844. }
  32845. this.setIndices(indices);
  32846. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32847. // Updating vertex buffers
  32848. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32849. kind = kinds[kindIndex];
  32850. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32851. }
  32852. // Updating submeshes
  32853. this.releaseSubMeshes();
  32854. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32855. var previousOne = previousSubmeshes[submeshIndex];
  32856. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32857. }
  32858. this.synchronizeInstances();
  32859. return this;
  32860. };
  32861. /**
  32862. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32863. * In other words, more vertices, no more indices and a single bigger VBO.
  32864. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32865. * Returns the Mesh.
  32866. */
  32867. Mesh.prototype.convertToUnIndexedMesh = function () {
  32868. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32869. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32870. var kinds = this.getVerticesDataKinds();
  32871. var vbs = {};
  32872. var data = {};
  32873. var newdata = {};
  32874. var kindIndex;
  32875. var kind;
  32876. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32877. kind = kinds[kindIndex];
  32878. var vertexBuffer = this.getVertexBuffer(kind);
  32879. vbs[kind] = vertexBuffer;
  32880. data[kind] = vbs[kind].getData();
  32881. newdata[kind] = [];
  32882. }
  32883. // Save previous submeshes
  32884. var previousSubmeshes = this.subMeshes.slice(0);
  32885. var indices = this.getIndices();
  32886. var totalIndices = this.getTotalIndices();
  32887. // Generating unique vertices per face
  32888. var index;
  32889. for (index = 0; index < totalIndices; index++) {
  32890. var vertexIndex = indices[index];
  32891. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32892. kind = kinds[kindIndex];
  32893. var stride = vbs[kind].getStrideSize();
  32894. for (var offset = 0; offset < stride; offset++) {
  32895. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32896. }
  32897. }
  32898. }
  32899. // Updating indices
  32900. for (index = 0; index < totalIndices; index += 3) {
  32901. indices[index] = index;
  32902. indices[index + 1] = index + 1;
  32903. indices[index + 2] = index + 2;
  32904. }
  32905. this.setIndices(indices);
  32906. // Updating vertex buffers
  32907. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32908. kind = kinds[kindIndex];
  32909. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32910. }
  32911. // Updating submeshes
  32912. this.releaseSubMeshes();
  32913. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32914. var previousOne = previousSubmeshes[submeshIndex];
  32915. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32916. }
  32917. this._unIndexed = true;
  32918. this.synchronizeInstances();
  32919. return this;
  32920. };
  32921. /**
  32922. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32923. * This method returns the Mesh.
  32924. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32925. */
  32926. Mesh.prototype.flipFaces = function (flipNormals) {
  32927. if (flipNormals === void 0) { flipNormals = false; }
  32928. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32929. var i;
  32930. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32931. for (i = 0; i < vertex_data.normals.length; i++) {
  32932. vertex_data.normals[i] *= -1;
  32933. }
  32934. }
  32935. if (vertex_data.indices) {
  32936. var temp;
  32937. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32938. // reassign indices
  32939. temp = vertex_data.indices[i + 1];
  32940. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32941. vertex_data.indices[i + 2] = temp;
  32942. }
  32943. }
  32944. vertex_data.applyToMesh(this);
  32945. return this;
  32946. };
  32947. // Instances
  32948. /**
  32949. * Creates a new InstancedMesh object from the mesh model.
  32950. * An instance shares the same properties and the same material than its model.
  32951. * Only these properties of each instance can then be set individually :
  32952. * - position
  32953. * - rotation
  32954. * - rotationQuaternion
  32955. * - setPivotMatrix
  32956. * - scaling
  32957. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32958. * Warning : this method is not supported for Line mesh and LineSystem
  32959. */
  32960. Mesh.prototype.createInstance = function (name) {
  32961. return new BABYLON.InstancedMesh(name, this);
  32962. };
  32963. /**
  32964. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32965. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32966. * This method returns the Mesh.
  32967. */
  32968. Mesh.prototype.synchronizeInstances = function () {
  32969. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32970. var instance = this.instances[instanceIndex];
  32971. instance._syncSubMeshes();
  32972. }
  32973. return this;
  32974. };
  32975. /**
  32976. * Simplify the mesh according to the given array of settings.
  32977. * Function will return immediately and will simplify async. It returns the Mesh.
  32978. * @param settings a collection of simplification settings.
  32979. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32980. * @param type the type of simplification to run.
  32981. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32982. */
  32983. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32984. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32985. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32986. this.getScene().simplificationQueue.addTask({
  32987. settings: settings,
  32988. parallelProcessing: parallelProcessing,
  32989. mesh: this,
  32990. simplificationType: simplificationType,
  32991. successCallback: successCallback
  32992. });
  32993. return this;
  32994. };
  32995. /**
  32996. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32997. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32998. * This should be used together with the simplification to avoid disappearing triangles.
  32999. * Returns the Mesh.
  33000. * @param successCallback an optional success callback to be called after the optimization finished.
  33001. */
  33002. Mesh.prototype.optimizeIndices = function (successCallback) {
  33003. var _this = this;
  33004. var indices = this.getIndices();
  33005. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33006. if (!positions || !indices) {
  33007. return this;
  33008. }
  33009. var vectorPositions = new Array();
  33010. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33011. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33012. }
  33013. var dupes = new Array();
  33014. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33015. var realPos = vectorPositions.length - 1 - iteration;
  33016. var testedPosition = vectorPositions[realPos];
  33017. for (var j = 0; j < realPos; ++j) {
  33018. var againstPosition = vectorPositions[j];
  33019. if (testedPosition.equals(againstPosition)) {
  33020. dupes[realPos] = j;
  33021. break;
  33022. }
  33023. }
  33024. }, function () {
  33025. for (var i = 0; i < indices.length; ++i) {
  33026. indices[i] = dupes[indices[i]] || indices[i];
  33027. }
  33028. //indices are now reordered
  33029. var originalSubMeshes = _this.subMeshes.slice(0);
  33030. _this.setIndices(indices);
  33031. _this.subMeshes = originalSubMeshes;
  33032. if (successCallback) {
  33033. successCallback(_this);
  33034. }
  33035. });
  33036. return this;
  33037. };
  33038. Mesh.prototype.serialize = function (serializationObject) {
  33039. serializationObject.name = this.name;
  33040. serializationObject.id = this.id;
  33041. serializationObject.type = this.getClassName();
  33042. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33043. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33044. }
  33045. serializationObject.position = this.position.asArray();
  33046. if (this.rotationQuaternion) {
  33047. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33048. }
  33049. else if (this.rotation) {
  33050. serializationObject.rotation = this.rotation.asArray();
  33051. }
  33052. serializationObject.scaling = this.scaling.asArray();
  33053. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33054. serializationObject.isEnabled = this.isEnabled(false);
  33055. serializationObject.isVisible = this.isVisible;
  33056. serializationObject.infiniteDistance = this.infiniteDistance;
  33057. serializationObject.pickable = this.isPickable;
  33058. serializationObject.receiveShadows = this.receiveShadows;
  33059. serializationObject.billboardMode = this.billboardMode;
  33060. serializationObject.visibility = this.visibility;
  33061. serializationObject.checkCollisions = this.checkCollisions;
  33062. serializationObject.isBlocker = this.isBlocker;
  33063. // Parent
  33064. if (this.parent) {
  33065. serializationObject.parentId = this.parent.id;
  33066. }
  33067. // Geometry
  33068. serializationObject.isUnIndexed = this.isUnIndexed;
  33069. var geometry = this._geometry;
  33070. if (geometry) {
  33071. var geometryId = geometry.id;
  33072. serializationObject.geometryId = geometryId;
  33073. // SubMeshes
  33074. serializationObject.subMeshes = [];
  33075. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33076. var subMesh = this.subMeshes[subIndex];
  33077. serializationObject.subMeshes.push({
  33078. materialIndex: subMesh.materialIndex,
  33079. verticesStart: subMesh.verticesStart,
  33080. verticesCount: subMesh.verticesCount,
  33081. indexStart: subMesh.indexStart,
  33082. indexCount: subMesh.indexCount
  33083. });
  33084. }
  33085. }
  33086. // Material
  33087. if (this.material) {
  33088. serializationObject.materialId = this.material.id;
  33089. }
  33090. else {
  33091. this.material = null;
  33092. }
  33093. // Morph targets
  33094. if (this.morphTargetManager) {
  33095. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33096. }
  33097. // Skeleton
  33098. if (this.skeleton) {
  33099. serializationObject.skeletonId = this.skeleton.id;
  33100. }
  33101. // Physics
  33102. //TODO implement correct serialization for physics impostors.
  33103. var impostor = this.getPhysicsImpostor();
  33104. if (impostor) {
  33105. serializationObject.physicsMass = impostor.getParam("mass");
  33106. serializationObject.physicsFriction = impostor.getParam("friction");
  33107. serializationObject.physicsRestitution = impostor.getParam("mass");
  33108. serializationObject.physicsImpostor = impostor.type;
  33109. }
  33110. // Metadata
  33111. if (this.metadata) {
  33112. serializationObject.metadata = this.metadata;
  33113. }
  33114. // Instances
  33115. serializationObject.instances = [];
  33116. for (var index = 0; index < this.instances.length; index++) {
  33117. var instance = this.instances[index];
  33118. var serializationInstance = {
  33119. name: instance.name,
  33120. id: instance.id,
  33121. position: instance.position.asArray(),
  33122. scaling: instance.scaling.asArray()
  33123. };
  33124. if (instance.rotationQuaternion) {
  33125. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33126. }
  33127. else if (instance.rotation) {
  33128. serializationInstance.rotation = instance.rotation.asArray();
  33129. }
  33130. serializationObject.instances.push(serializationInstance);
  33131. // Animations
  33132. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33133. serializationInstance.ranges = instance.serializeAnimationRanges();
  33134. }
  33135. //
  33136. // Animations
  33137. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33138. serializationObject.ranges = this.serializeAnimationRanges();
  33139. // Layer mask
  33140. serializationObject.layerMask = this.layerMask;
  33141. // Alpha
  33142. serializationObject.alphaIndex = this.alphaIndex;
  33143. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33144. // Overlay
  33145. serializationObject.overlayAlpha = this.overlayAlpha;
  33146. serializationObject.overlayColor = this.overlayColor.asArray();
  33147. serializationObject.renderOverlay = this.renderOverlay;
  33148. // Fog
  33149. serializationObject.applyFog = this.applyFog;
  33150. // Action Manager
  33151. if (this.actionManager) {
  33152. serializationObject.actions = this.actionManager.serialize(this.name);
  33153. }
  33154. };
  33155. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33156. if (!this.geometry) {
  33157. return;
  33158. }
  33159. this._markSubMeshesAsAttributesDirty();
  33160. var morphTargetManager = this._morphTargetManager;
  33161. if (morphTargetManager && morphTargetManager.vertexCount) {
  33162. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33163. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33164. this.morphTargetManager = null;
  33165. return;
  33166. }
  33167. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33168. var morphTarget = morphTargetManager.getActiveTarget(index);
  33169. var positions = morphTarget.getPositions();
  33170. if (!positions) {
  33171. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33172. return;
  33173. }
  33174. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33175. var normals = morphTarget.getNormals();
  33176. if (normals) {
  33177. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33178. }
  33179. var tangents = morphTarget.getTangents();
  33180. if (tangents) {
  33181. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33182. }
  33183. }
  33184. }
  33185. else {
  33186. var index = 0;
  33187. // Positions
  33188. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33189. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33190. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33191. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33192. }
  33193. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33194. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33195. }
  33196. index++;
  33197. }
  33198. }
  33199. };
  33200. // Statics
  33201. /**
  33202. * Returns a new Mesh object parsed from the source provided.
  33203. * The parameter `parsedMesh` is the source.
  33204. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33205. */
  33206. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33207. var mesh;
  33208. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33209. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33210. }
  33211. else {
  33212. mesh = new Mesh(parsedMesh.name, scene);
  33213. }
  33214. mesh.id = parsedMesh.id;
  33215. if (BABYLON.Tags) {
  33216. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33217. }
  33218. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33219. if (parsedMesh.metadata !== undefined) {
  33220. mesh.metadata = parsedMesh.metadata;
  33221. }
  33222. if (parsedMesh.rotationQuaternion) {
  33223. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33224. }
  33225. else if (parsedMesh.rotation) {
  33226. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33227. }
  33228. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33229. if (parsedMesh.localMatrix) {
  33230. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33231. }
  33232. else if (parsedMesh.pivotMatrix) {
  33233. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33234. }
  33235. mesh.setEnabled(parsedMesh.isEnabled);
  33236. mesh.isVisible = parsedMesh.isVisible;
  33237. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33238. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33239. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33240. if (parsedMesh.applyFog !== undefined) {
  33241. mesh.applyFog = parsedMesh.applyFog;
  33242. }
  33243. if (parsedMesh.pickable !== undefined) {
  33244. mesh.isPickable = parsedMesh.pickable;
  33245. }
  33246. if (parsedMesh.alphaIndex !== undefined) {
  33247. mesh.alphaIndex = parsedMesh.alphaIndex;
  33248. }
  33249. mesh.receiveShadows = parsedMesh.receiveShadows;
  33250. mesh.billboardMode = parsedMesh.billboardMode;
  33251. if (parsedMesh.visibility !== undefined) {
  33252. mesh.visibility = parsedMesh.visibility;
  33253. }
  33254. mesh.checkCollisions = parsedMesh.checkCollisions;
  33255. if (parsedMesh.isBlocker !== undefined) {
  33256. mesh.isBlocker = parsedMesh.isBlocker;
  33257. }
  33258. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33259. // freezeWorldMatrix
  33260. if (parsedMesh.freezeWorldMatrix) {
  33261. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33262. }
  33263. // Parent
  33264. if (parsedMesh.parentId) {
  33265. mesh._waitingParentId = parsedMesh.parentId;
  33266. }
  33267. // Actions
  33268. if (parsedMesh.actions !== undefined) {
  33269. mesh._waitingActions = parsedMesh.actions;
  33270. }
  33271. // Overlay
  33272. if (parsedMesh.overlayAlpha !== undefined) {
  33273. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33274. }
  33275. if (parsedMesh.overlayColor !== undefined) {
  33276. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33277. }
  33278. if (parsedMesh.renderOverlay !== undefined) {
  33279. mesh.renderOverlay = parsedMesh.renderOverlay;
  33280. }
  33281. // Geometry
  33282. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33283. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33284. if (parsedMesh.delayLoadingFile) {
  33285. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33286. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33287. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33288. if (parsedMesh._binaryInfo) {
  33289. mesh._binaryInfo = parsedMesh._binaryInfo;
  33290. }
  33291. mesh._delayInfo = [];
  33292. if (parsedMesh.hasUVs) {
  33293. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33294. }
  33295. if (parsedMesh.hasUVs2) {
  33296. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33297. }
  33298. if (parsedMesh.hasUVs3) {
  33299. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33300. }
  33301. if (parsedMesh.hasUVs4) {
  33302. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33303. }
  33304. if (parsedMesh.hasUVs5) {
  33305. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33306. }
  33307. if (parsedMesh.hasUVs6) {
  33308. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33309. }
  33310. if (parsedMesh.hasColors) {
  33311. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33312. }
  33313. if (parsedMesh.hasMatricesIndices) {
  33314. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33315. }
  33316. if (parsedMesh.hasMatricesWeights) {
  33317. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33318. }
  33319. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33320. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33321. mesh._checkDelayState();
  33322. }
  33323. }
  33324. else {
  33325. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33326. }
  33327. // Material
  33328. if (parsedMesh.materialId) {
  33329. mesh.setMaterialByID(parsedMesh.materialId);
  33330. }
  33331. else {
  33332. mesh.material = null;
  33333. }
  33334. // Morph targets
  33335. if (parsedMesh.morphTargetManagerId > -1) {
  33336. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33337. }
  33338. // Skeleton
  33339. if (parsedMesh.skeletonId > -1) {
  33340. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33341. if (parsedMesh.numBoneInfluencers) {
  33342. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33343. }
  33344. }
  33345. // Animations
  33346. if (parsedMesh.animations) {
  33347. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33348. var parsedAnimation = parsedMesh.animations[animationIndex];
  33349. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33350. }
  33351. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33352. }
  33353. if (parsedMesh.autoAnimate) {
  33354. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33355. }
  33356. // Layer Mask
  33357. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33358. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33359. }
  33360. else {
  33361. mesh.layerMask = 0x0FFFFFFF;
  33362. }
  33363. // Physics
  33364. if (parsedMesh.physicsImpostor) {
  33365. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33366. mass: parsedMesh.physicsMass,
  33367. friction: parsedMesh.physicsFriction,
  33368. restitution: parsedMesh.physicsRestitution
  33369. }, scene);
  33370. }
  33371. // Instances
  33372. if (parsedMesh.instances) {
  33373. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33374. var parsedInstance = parsedMesh.instances[index];
  33375. var instance = mesh.createInstance(parsedInstance.name);
  33376. if (parsedInstance.id) {
  33377. instance.id = parsedInstance.id;
  33378. }
  33379. if (BABYLON.Tags) {
  33380. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33381. }
  33382. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33383. if (parsedInstance.parentId) {
  33384. instance._waitingParentId = parsedInstance.parentId;
  33385. }
  33386. if (parsedInstance.rotationQuaternion) {
  33387. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33388. }
  33389. else if (parsedInstance.rotation) {
  33390. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33391. }
  33392. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33393. instance.checkCollisions = mesh.checkCollisions;
  33394. if (parsedMesh.animations) {
  33395. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33396. parsedAnimation = parsedMesh.animations[animationIndex];
  33397. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33398. }
  33399. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33400. }
  33401. }
  33402. }
  33403. return mesh;
  33404. };
  33405. /**
  33406. * Creates a ribbon mesh.
  33407. * Please consider using the same method from the MeshBuilder class instead.
  33408. * 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.
  33409. *
  33410. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33411. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33412. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33413. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33414. * 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.
  33415. * 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.
  33416. * 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
  33417. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33418. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33419. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33420. */
  33421. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33422. if (closeArray === void 0) { closeArray = false; }
  33423. if (updatable === void 0) { updatable = false; }
  33424. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33425. pathArray: pathArray,
  33426. closeArray: closeArray,
  33427. closePath: closePath,
  33428. offset: offset,
  33429. updatable: updatable,
  33430. sideOrientation: sideOrientation,
  33431. instance: instance
  33432. }, scene);
  33433. };
  33434. /**
  33435. * Creates a plane polygonal mesh. By default, this is a disc.
  33436. * Please consider using the same method from the MeshBuilder class instead.
  33437. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33438. * 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.
  33439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33440. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33442. */
  33443. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33444. if (scene === void 0) { scene = null; }
  33445. var options = {
  33446. radius: radius,
  33447. tessellation: tessellation,
  33448. sideOrientation: sideOrientation,
  33449. updatable: updatable
  33450. };
  33451. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33452. };
  33453. /**
  33454. * Creates a box mesh.
  33455. * Please consider using the same method from the MeshBuilder class instead.
  33456. * The parameter `size` sets the size (float) of each box side (default 1).
  33457. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33458. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33459. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33460. */
  33461. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33462. if (scene === void 0) { scene = null; }
  33463. var options = {
  33464. size: size,
  33465. sideOrientation: sideOrientation,
  33466. updatable: updatable
  33467. };
  33468. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33469. };
  33470. /**
  33471. * Creates a sphere mesh.
  33472. * Please consider using the same method from the MeshBuilder class instead.
  33473. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33474. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33475. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33476. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33477. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33478. */
  33479. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33480. var options = {
  33481. segments: segments,
  33482. diameterX: diameter,
  33483. diameterY: diameter,
  33484. diameterZ: diameter,
  33485. sideOrientation: sideOrientation,
  33486. updatable: updatable
  33487. };
  33488. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33489. };
  33490. /**
  33491. * Creates a cylinder or a cone mesh.
  33492. * Please consider using the same method from the MeshBuilder class instead.
  33493. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33494. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33495. * 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.
  33496. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33497. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33498. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33499. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33500. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33501. */
  33502. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33503. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33504. if (scene !== undefined) {
  33505. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33506. updatable = scene;
  33507. }
  33508. scene = subdivisions;
  33509. subdivisions = 1;
  33510. }
  33511. var options = {
  33512. height: height,
  33513. diameterTop: diameterTop,
  33514. diameterBottom: diameterBottom,
  33515. tessellation: tessellation,
  33516. subdivisions: subdivisions,
  33517. sideOrientation: sideOrientation,
  33518. updatable: updatable
  33519. };
  33520. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33521. };
  33522. // Torus (Code from SharpDX.org)
  33523. /**
  33524. * Creates a torus mesh.
  33525. * Please consider using the same method from the MeshBuilder class instead.
  33526. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33527. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33528. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33529. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33530. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33531. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33532. */
  33533. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33534. var options = {
  33535. diameter: diameter,
  33536. thickness: thickness,
  33537. tessellation: tessellation,
  33538. sideOrientation: sideOrientation,
  33539. updatable: updatable
  33540. };
  33541. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33542. };
  33543. /**
  33544. * Creates a torus knot mesh.
  33545. * Please consider using the same method from the MeshBuilder class instead.
  33546. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33547. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33548. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33549. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33550. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33551. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33552. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33553. */
  33554. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33555. var options = {
  33556. radius: radius,
  33557. tube: tube,
  33558. radialSegments: radialSegments,
  33559. tubularSegments: tubularSegments,
  33560. p: p,
  33561. q: q,
  33562. sideOrientation: sideOrientation,
  33563. updatable: updatable
  33564. };
  33565. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33566. };
  33567. /**
  33568. * Creates a line mesh.
  33569. * Please consider using the same method from the MeshBuilder class instead.
  33570. * 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.
  33571. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33572. * The parameter `points` is an array successive Vector3.
  33573. * 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
  33574. * When updating an instance, remember that only point positions can change, not the number of points.
  33575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33576. */
  33577. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33578. if (scene === void 0) { scene = null; }
  33579. if (updatable === void 0) { updatable = false; }
  33580. if (instance === void 0) { instance = null; }
  33581. var options = {
  33582. points: points,
  33583. updatable: updatable,
  33584. instance: instance
  33585. };
  33586. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33587. };
  33588. /**
  33589. * Creates a dashed line mesh.
  33590. * Please consider using the same method from the MeshBuilder class instead.
  33591. * 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.
  33592. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33593. * The parameter `points` is an array successive Vector3.
  33594. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33595. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33596. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33597. * 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
  33598. * When updating an instance, remember that only point positions can change, not the number of points.
  33599. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33600. */
  33601. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33602. if (scene === void 0) { scene = null; }
  33603. var options = {
  33604. points: points,
  33605. dashSize: dashSize,
  33606. gapSize: gapSize,
  33607. dashNb: dashNb,
  33608. updatable: updatable,
  33609. instance: instance
  33610. };
  33611. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33612. };
  33613. /**
  33614. * Creates a polygon mesh.
  33615. * Please consider using the same method from the MeshBuilder class instead.
  33616. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33617. * 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.
  33618. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33619. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33620. * Remember you can only change the shape positions, not their number when updating a polygon.
  33621. */
  33622. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33623. var options = {
  33624. shape: shape,
  33625. holes: holes,
  33626. updatable: updatable,
  33627. sideOrientation: sideOrientation
  33628. };
  33629. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33630. };
  33631. /**
  33632. * Creates an extruded polygon mesh, with depth in the Y direction.
  33633. * Please consider using the same method from the MeshBuilder class instead.
  33634. */
  33635. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33636. var options = {
  33637. shape: shape,
  33638. holes: holes,
  33639. depth: depth,
  33640. updatable: updatable,
  33641. sideOrientation: sideOrientation
  33642. };
  33643. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33644. };
  33645. /**
  33646. * Creates an extruded shape mesh.
  33647. * 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.
  33648. * Please consider using the same method from the MeshBuilder class instead.
  33649. *
  33650. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33651. * 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
  33652. * extruded along the Z axis.
  33653. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33654. * 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.
  33655. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33656. * 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
  33657. * 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
  33658. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33659. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33660. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33661. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33662. */
  33663. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33664. if (scene === void 0) { scene = null; }
  33665. var options = {
  33666. shape: shape,
  33667. path: path,
  33668. scale: scale,
  33669. rotation: rotation,
  33670. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33671. sideOrientation: sideOrientation,
  33672. instance: instance,
  33673. updatable: updatable
  33674. };
  33675. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33676. };
  33677. /**
  33678. * Creates an custom extruded shape mesh.
  33679. * 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.
  33680. * Please consider using the same method from the MeshBuilder class instead.
  33681. *
  33682. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33683. * 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
  33684. * extruded along the Z axis.
  33685. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33686. * 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
  33687. * and the distance of this point from the begining of the path :
  33688. * ```javascript
  33689. * var rotationFunction = function(i, distance) {
  33690. * // do things
  33691. * return rotationValue; }
  33692. * ```
  33693. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33694. * 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
  33695. * and the distance of this point from the begining of the path :
  33696. * ```javascript
  33697. * var scaleFunction = function(i, distance) {
  33698. * // do things
  33699. * return scaleValue;}
  33700. * ```
  33701. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33702. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33703. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33704. * 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
  33705. * 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
  33706. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33707. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33708. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33709. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33710. */
  33711. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33712. var options = {
  33713. shape: shape,
  33714. path: path,
  33715. scaleFunction: scaleFunction,
  33716. rotationFunction: rotationFunction,
  33717. ribbonCloseArray: ribbonCloseArray,
  33718. ribbonClosePath: ribbonClosePath,
  33719. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33720. sideOrientation: sideOrientation,
  33721. instance: instance,
  33722. updatable: updatable
  33723. };
  33724. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33725. };
  33726. /**
  33727. * Creates lathe mesh.
  33728. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33729. * Please consider using the same method from the MeshBuilder class instead.
  33730. * 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
  33731. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33732. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33733. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33734. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33735. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33736. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33737. */
  33738. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33739. var options = {
  33740. shape: shape,
  33741. radius: radius,
  33742. tessellation: tessellation,
  33743. sideOrientation: sideOrientation,
  33744. updatable: updatable
  33745. };
  33746. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33747. };
  33748. /**
  33749. * Creates a plane mesh.
  33750. * Please consider using the same method from the MeshBuilder class instead.
  33751. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33752. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33753. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33754. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33755. */
  33756. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33757. var options = {
  33758. size: size,
  33759. width: size,
  33760. height: size,
  33761. sideOrientation: sideOrientation,
  33762. updatable: updatable
  33763. };
  33764. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33765. };
  33766. /**
  33767. * Creates a ground mesh.
  33768. * Please consider using the same method from the MeshBuilder class instead.
  33769. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33770. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33771. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33772. */
  33773. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33774. var options = {
  33775. width: width,
  33776. height: height,
  33777. subdivisions: subdivisions,
  33778. updatable: updatable
  33779. };
  33780. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33781. };
  33782. /**
  33783. * Creates a tiled ground mesh.
  33784. * Please consider using the same method from the MeshBuilder class instead.
  33785. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33786. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33787. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33788. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33789. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33790. * numbers of subdivisions on the ground width and height of each tile.
  33791. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33792. */
  33793. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33794. var options = {
  33795. xmin: xmin,
  33796. zmin: zmin,
  33797. xmax: xmax,
  33798. zmax: zmax,
  33799. subdivisions: subdivisions,
  33800. precision: precision,
  33801. updatable: updatable
  33802. };
  33803. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33804. };
  33805. /**
  33806. * Creates a ground mesh from a height map.
  33807. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33808. * Please consider using the same method from the MeshBuilder class instead.
  33809. * The parameter `url` sets the URL of the height map image resource.
  33810. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33811. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33812. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33813. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33814. * 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).
  33815. * This function is passed the newly built mesh :
  33816. * ```javascript
  33817. * function(mesh) { // do things
  33818. * return; }
  33819. * ```
  33820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33821. */
  33822. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33823. var options = {
  33824. width: width,
  33825. height: height,
  33826. subdivisions: subdivisions,
  33827. minHeight: minHeight,
  33828. maxHeight: maxHeight,
  33829. updatable: updatable,
  33830. onReady: onReady
  33831. };
  33832. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33833. };
  33834. /**
  33835. * Creates a tube mesh.
  33836. * 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.
  33837. * Please consider using the same method from the MeshBuilder class instead.
  33838. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33839. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33840. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33841. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33842. * 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.
  33843. * It must return a radius value (positive float) :
  33844. * ```javascript
  33845. * var radiusFunction = function(i, distance) {
  33846. * // do things
  33847. * return radius; }
  33848. * ```
  33849. * 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
  33850. * 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
  33851. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33852. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33853. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33854. */
  33855. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33856. var options = {
  33857. path: path,
  33858. radius: radius,
  33859. tessellation: tessellation,
  33860. radiusFunction: radiusFunction,
  33861. arc: 1,
  33862. cap: cap,
  33863. updatable: updatable,
  33864. sideOrientation: sideOrientation,
  33865. instance: instance
  33866. };
  33867. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33868. };
  33869. /**
  33870. * Creates a polyhedron mesh.
  33871. * Please consider using the same method from the MeshBuilder class instead.
  33872. * 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
  33873. * to choose the wanted type.
  33874. * The parameter `size` (positive float, default 1) sets the polygon size.
  33875. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33876. * 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`.
  33877. * 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
  33878. * 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)`).
  33879. * 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
  33880. * 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.
  33881. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33882. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33883. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33884. */
  33885. Mesh.CreatePolyhedron = function (name, options, scene) {
  33886. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33887. };
  33888. /**
  33889. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33890. * Please consider using the same method from the MeshBuilder class instead.
  33891. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33892. * 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`).
  33893. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33894. * 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.
  33895. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33896. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33897. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33898. */
  33899. Mesh.CreateIcoSphere = function (name, options, scene) {
  33900. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33901. };
  33902. /**
  33903. * Creates a decal mesh.
  33904. * Please consider using the same method from the MeshBuilder class instead.
  33905. * 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.
  33906. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33907. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33908. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33909. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33910. */
  33911. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33912. var options = {
  33913. position: position,
  33914. normal: normal,
  33915. size: size,
  33916. angle: angle
  33917. };
  33918. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33919. };
  33920. // Skeletons
  33921. /**
  33922. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33923. */
  33924. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33925. if (!this._sourcePositions) {
  33926. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33927. if (!source) {
  33928. return this._sourcePositions;
  33929. }
  33930. this._sourcePositions = new Float32Array(source);
  33931. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33932. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33933. }
  33934. }
  33935. return this._sourcePositions;
  33936. };
  33937. /**
  33938. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33939. */
  33940. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33941. if (!this._sourceNormals) {
  33942. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33943. if (!source) {
  33944. return this._sourceNormals;
  33945. }
  33946. this._sourceNormals = new Float32Array(source);
  33947. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33948. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33949. }
  33950. }
  33951. return this._sourceNormals;
  33952. };
  33953. /**
  33954. * Updates the vertex buffer by applying transformation from the bones.
  33955. * Returns the Mesh.
  33956. *
  33957. * @param {skeleton} skeleton to apply
  33958. */
  33959. Mesh.prototype.applySkeleton = function (skeleton) {
  33960. if (!this.geometry) {
  33961. return this;
  33962. }
  33963. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33964. return this;
  33965. }
  33966. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33967. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33968. return this;
  33969. }
  33970. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33971. return this;
  33972. }
  33973. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33974. return this;
  33975. }
  33976. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33977. return this;
  33978. }
  33979. if (!this._sourcePositions) {
  33980. var submeshes = this.subMeshes.slice();
  33981. this.setPositionsForCPUSkinning();
  33982. this.subMeshes = submeshes;
  33983. }
  33984. if (!this._sourceNormals) {
  33985. this.setNormalsForCPUSkinning();
  33986. }
  33987. // positionsData checks for not being Float32Array will only pass at most once
  33988. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33989. if (!positionsData) {
  33990. return this;
  33991. }
  33992. if (!(positionsData instanceof Float32Array)) {
  33993. positionsData = new Float32Array(positionsData);
  33994. }
  33995. // normalsData checks for not being Float32Array will only pass at most once
  33996. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33997. if (!normalsData) {
  33998. return this;
  33999. }
  34000. if (!(normalsData instanceof Float32Array)) {
  34001. normalsData = new Float32Array(normalsData);
  34002. }
  34003. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34004. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34005. if (!matricesWeightsData || !matricesIndicesData) {
  34006. return this;
  34007. }
  34008. var needExtras = this.numBoneInfluencers > 4;
  34009. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34010. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34011. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34012. var tempVector3 = BABYLON.Vector3.Zero();
  34013. var finalMatrix = new BABYLON.Matrix();
  34014. var tempMatrix = new BABYLON.Matrix();
  34015. var matWeightIdx = 0;
  34016. var inf;
  34017. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34018. var weight;
  34019. for (inf = 0; inf < 4; inf++) {
  34020. weight = matricesWeightsData[matWeightIdx + inf];
  34021. if (weight > 0) {
  34022. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34023. finalMatrix.addToSelf(tempMatrix);
  34024. }
  34025. else
  34026. break;
  34027. }
  34028. if (needExtras) {
  34029. for (inf = 0; inf < 4; inf++) {
  34030. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34031. if (weight > 0) {
  34032. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34033. finalMatrix.addToSelf(tempMatrix);
  34034. }
  34035. else
  34036. break;
  34037. }
  34038. }
  34039. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34040. tempVector3.toArray(positionsData, index);
  34041. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34042. tempVector3.toArray(normalsData, index);
  34043. finalMatrix.reset();
  34044. }
  34045. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34046. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34047. return this;
  34048. };
  34049. // Tools
  34050. /**
  34051. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34052. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34053. */
  34054. Mesh.MinMax = function (meshes) {
  34055. var minVector = null;
  34056. var maxVector = null;
  34057. meshes.forEach(function (mesh, index, array) {
  34058. var boundingInfo = mesh.getBoundingInfo();
  34059. var boundingBox = boundingInfo.boundingBox;
  34060. if (!minVector || !maxVector) {
  34061. minVector = boundingBox.minimumWorld;
  34062. maxVector = boundingBox.maximumWorld;
  34063. }
  34064. else {
  34065. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34066. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34067. }
  34068. });
  34069. if (!minVector || !maxVector) {
  34070. return {
  34071. min: BABYLON.Vector3.Zero(),
  34072. max: BABYLON.Vector3.Zero()
  34073. };
  34074. }
  34075. return {
  34076. min: minVector,
  34077. max: maxVector
  34078. };
  34079. };
  34080. /**
  34081. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34082. */
  34083. Mesh.Center = function (meshesOrMinMaxVector) {
  34084. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34085. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34086. };
  34087. /**
  34088. * Merge the array of meshes into a single mesh for performance reasons.
  34089. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34090. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34091. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34092. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34093. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34094. */
  34095. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34096. if (disposeSource === void 0) { disposeSource = true; }
  34097. var index;
  34098. if (!allow32BitsIndices) {
  34099. var totalVertices = 0;
  34100. // Counting vertices
  34101. for (index = 0; index < meshes.length; index++) {
  34102. if (meshes[index]) {
  34103. totalVertices += meshes[index].getTotalVertices();
  34104. if (totalVertices > 65536) {
  34105. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34106. return null;
  34107. }
  34108. }
  34109. }
  34110. }
  34111. // Merge
  34112. var vertexData = null;
  34113. var otherVertexData;
  34114. var indiceArray = new Array();
  34115. var source = null;
  34116. for (index = 0; index < meshes.length; index++) {
  34117. if (meshes[index]) {
  34118. meshes[index].computeWorldMatrix(true);
  34119. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  34120. otherVertexData.transform(meshes[index].getWorldMatrix());
  34121. if (vertexData) {
  34122. vertexData.merge(otherVertexData);
  34123. }
  34124. else {
  34125. vertexData = otherVertexData;
  34126. source = meshes[index];
  34127. }
  34128. if (subdivideWithSubMeshes) {
  34129. indiceArray.push(meshes[index].getTotalIndices());
  34130. }
  34131. }
  34132. }
  34133. source = source;
  34134. if (!meshSubclass) {
  34135. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34136. }
  34137. vertexData.applyToMesh(meshSubclass);
  34138. // Setting properties
  34139. meshSubclass.material = source.material;
  34140. meshSubclass.checkCollisions = source.checkCollisions;
  34141. // Cleaning
  34142. if (disposeSource) {
  34143. for (index = 0; index < meshes.length; index++) {
  34144. if (meshes[index]) {
  34145. meshes[index].dispose();
  34146. }
  34147. }
  34148. }
  34149. // Subdivide
  34150. if (subdivideWithSubMeshes) {
  34151. //-- Suppresions du submesh global
  34152. meshSubclass.releaseSubMeshes();
  34153. index = 0;
  34154. var offset = 0;
  34155. //-- aplique la subdivision en fonction du tableau d'indices
  34156. while (index < indiceArray.length) {
  34157. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34158. offset += indiceArray[index];
  34159. index++;
  34160. }
  34161. }
  34162. return meshSubclass;
  34163. };
  34164. // Consts
  34165. Mesh._FRONTSIDE = 0;
  34166. Mesh._BACKSIDE = 1;
  34167. Mesh._DOUBLESIDE = 2;
  34168. Mesh._DEFAULTSIDE = 0;
  34169. Mesh._NO_CAP = 0;
  34170. Mesh._CAP_START = 1;
  34171. Mesh._CAP_END = 2;
  34172. Mesh._CAP_ALL = 3;
  34173. return Mesh;
  34174. }(BABYLON.AbstractMesh));
  34175. BABYLON.Mesh = Mesh;
  34176. })(BABYLON || (BABYLON = {}));
  34177. //# sourceMappingURL=babylon.mesh.js.map
  34178. var BABYLON;
  34179. (function (BABYLON) {
  34180. var BaseSubMesh = /** @class */ (function () {
  34181. function BaseSubMesh() {
  34182. }
  34183. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34184. get: function () {
  34185. return this._materialEffect;
  34186. },
  34187. enumerable: true,
  34188. configurable: true
  34189. });
  34190. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34191. if (defines === void 0) { defines = null; }
  34192. if (this._materialEffect === effect) {
  34193. if (!effect) {
  34194. this._materialDefines = null;
  34195. }
  34196. return;
  34197. }
  34198. this._materialDefines = defines;
  34199. this._materialEffect = effect;
  34200. };
  34201. return BaseSubMesh;
  34202. }());
  34203. BABYLON.BaseSubMesh = BaseSubMesh;
  34204. var SubMesh = /** @class */ (function (_super) {
  34205. __extends(SubMesh, _super);
  34206. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34207. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34208. var _this = _super.call(this) || this;
  34209. _this.materialIndex = materialIndex;
  34210. _this.verticesStart = verticesStart;
  34211. _this.verticesCount = verticesCount;
  34212. _this.indexStart = indexStart;
  34213. _this.indexCount = indexCount;
  34214. _this._renderId = 0;
  34215. _this._mesh = mesh;
  34216. _this._renderingMesh = renderingMesh || mesh;
  34217. mesh.subMeshes.push(_this);
  34218. _this._trianglePlanes = [];
  34219. _this._id = mesh.subMeshes.length - 1;
  34220. if (createBoundingBox) {
  34221. _this.refreshBoundingInfo();
  34222. mesh.computeWorldMatrix(true);
  34223. }
  34224. return _this;
  34225. }
  34226. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34227. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34228. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34229. };
  34230. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34231. get: function () {
  34232. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34233. },
  34234. enumerable: true,
  34235. configurable: true
  34236. });
  34237. /**
  34238. * Returns the submesh BoudingInfo object.
  34239. */
  34240. SubMesh.prototype.getBoundingInfo = function () {
  34241. if (this.IsGlobal) {
  34242. return this._mesh.getBoundingInfo();
  34243. }
  34244. return this._boundingInfo;
  34245. };
  34246. /**
  34247. * Sets the submesh BoundingInfo.
  34248. * Return the SubMesh.
  34249. */
  34250. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34251. this._boundingInfo = boundingInfo;
  34252. return this;
  34253. };
  34254. /**
  34255. * Returns the mesh of the current submesh.
  34256. */
  34257. SubMesh.prototype.getMesh = function () {
  34258. return this._mesh;
  34259. };
  34260. /**
  34261. * Returns the rendering mesh of the submesh.
  34262. */
  34263. SubMesh.prototype.getRenderingMesh = function () {
  34264. return this._renderingMesh;
  34265. };
  34266. /**
  34267. * Returns the submesh material.
  34268. */
  34269. SubMesh.prototype.getMaterial = function () {
  34270. var rootMaterial = this._renderingMesh.material;
  34271. if (rootMaterial === null || rootMaterial === undefined) {
  34272. return this._mesh.getScene().defaultMaterial;
  34273. }
  34274. else if (rootMaterial.getSubMaterial) {
  34275. var multiMaterial = rootMaterial;
  34276. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34277. if (this._currentMaterial !== effectiveMaterial) {
  34278. this._currentMaterial = effectiveMaterial;
  34279. this._materialDefines = null;
  34280. }
  34281. return effectiveMaterial;
  34282. }
  34283. return rootMaterial;
  34284. };
  34285. // Methods
  34286. /**
  34287. * Sets a new updated BoundingInfo object to the submesh.
  34288. * Returns the SubMesh.
  34289. */
  34290. SubMesh.prototype.refreshBoundingInfo = function () {
  34291. this._lastColliderWorldVertices = null;
  34292. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34293. return this;
  34294. }
  34295. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34296. if (!data) {
  34297. this._boundingInfo = this._mesh.getBoundingInfo();
  34298. return this;
  34299. }
  34300. var indices = this._renderingMesh.getIndices();
  34301. var extend;
  34302. //is this the only submesh?
  34303. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34304. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34305. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34306. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34307. }
  34308. else {
  34309. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34310. }
  34311. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34312. return this;
  34313. };
  34314. SubMesh.prototype._checkCollision = function (collider) {
  34315. var boundingInfo = this.getBoundingInfo();
  34316. return boundingInfo._checkCollision(collider);
  34317. };
  34318. /**
  34319. * Updates the submesh BoundingInfo.
  34320. * Returns the Submesh.
  34321. */
  34322. SubMesh.prototype.updateBoundingInfo = function (world) {
  34323. var boundingInfo = this.getBoundingInfo();
  34324. if (!boundingInfo) {
  34325. this.refreshBoundingInfo();
  34326. boundingInfo = this.getBoundingInfo();
  34327. }
  34328. boundingInfo.update(world);
  34329. return this;
  34330. };
  34331. /**
  34332. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34333. * Boolean returned.
  34334. */
  34335. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34336. var boundingInfo = this.getBoundingInfo();
  34337. if (!boundingInfo) {
  34338. return false;
  34339. }
  34340. return boundingInfo.isInFrustum(frustumPlanes);
  34341. };
  34342. /**
  34343. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34344. * Boolean returned.
  34345. */
  34346. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34347. var boundingInfo = this.getBoundingInfo();
  34348. if (!boundingInfo) {
  34349. return false;
  34350. }
  34351. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34352. };
  34353. /**
  34354. * Renders the submesh.
  34355. * Returns it.
  34356. */
  34357. SubMesh.prototype.render = function (enableAlphaMode) {
  34358. this._renderingMesh.render(this, enableAlphaMode);
  34359. return this;
  34360. };
  34361. /**
  34362. * Returns a new Index Buffer.
  34363. * Type returned : WebGLBuffer.
  34364. */
  34365. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34366. if (!this._linesIndexBuffer) {
  34367. var linesIndices = [];
  34368. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34369. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34370. }
  34371. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34372. this.linesIndexCount = linesIndices.length;
  34373. }
  34374. return this._linesIndexBuffer;
  34375. };
  34376. /**
  34377. * True is the passed Ray intersects the submesh bounding box.
  34378. * Boolean returned.
  34379. */
  34380. SubMesh.prototype.canIntersects = function (ray) {
  34381. var boundingInfo = this.getBoundingInfo();
  34382. if (!boundingInfo) {
  34383. return false;
  34384. }
  34385. return ray.intersectsBox(boundingInfo.boundingBox);
  34386. };
  34387. /**
  34388. * Returns an object IntersectionInfo.
  34389. */
  34390. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34391. var intersectInfo = null;
  34392. var material = this.getMaterial();
  34393. if (!material) {
  34394. return null;
  34395. }
  34396. switch (material.fillMode) {
  34397. case BABYLON.Material.PointListDrawMode:
  34398. case BABYLON.Material.LineListDrawMode:
  34399. case BABYLON.Material.LineLoopDrawMode:
  34400. case BABYLON.Material.LineStripDrawMode:
  34401. case BABYLON.Material.TriangleFanDrawMode:
  34402. case BABYLON.Material.TriangleStripDrawMode:
  34403. return null;
  34404. }
  34405. // LineMesh first as it's also a Mesh...
  34406. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34407. var lineMesh = this._mesh;
  34408. // Line test
  34409. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34410. var p0 = positions[indices[index]];
  34411. var p1 = positions[indices[index + 1]];
  34412. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34413. if (length < 0) {
  34414. continue;
  34415. }
  34416. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34417. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34418. if (fastCheck) {
  34419. break;
  34420. }
  34421. }
  34422. }
  34423. }
  34424. else {
  34425. // Triangles test
  34426. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34427. var p0 = positions[indices[index]];
  34428. var p1 = positions[indices[index + 1]];
  34429. var p2 = positions[indices[index + 2]];
  34430. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34431. if (currentIntersectInfo) {
  34432. if (currentIntersectInfo.distance < 0) {
  34433. continue;
  34434. }
  34435. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34436. intersectInfo = currentIntersectInfo;
  34437. intersectInfo.faceId = index / 3;
  34438. if (fastCheck) {
  34439. break;
  34440. }
  34441. }
  34442. }
  34443. }
  34444. }
  34445. return intersectInfo;
  34446. };
  34447. SubMesh.prototype._rebuild = function () {
  34448. if (this._linesIndexBuffer) {
  34449. this._linesIndexBuffer = null;
  34450. }
  34451. };
  34452. // Clone
  34453. /**
  34454. * Creates a new Submesh from the passed Mesh.
  34455. */
  34456. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34457. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34458. if (!this.IsGlobal) {
  34459. var boundingInfo = this.getBoundingInfo();
  34460. if (!boundingInfo) {
  34461. return result;
  34462. }
  34463. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34464. }
  34465. return result;
  34466. };
  34467. // Dispose
  34468. /**
  34469. * Disposes the Submesh.
  34470. * Returns nothing.
  34471. */
  34472. SubMesh.prototype.dispose = function () {
  34473. if (this._linesIndexBuffer) {
  34474. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34475. this._linesIndexBuffer = null;
  34476. }
  34477. // Remove from mesh
  34478. var index = this._mesh.subMeshes.indexOf(this);
  34479. this._mesh.subMeshes.splice(index, 1);
  34480. };
  34481. // Statics
  34482. /**
  34483. * Creates a new Submesh from the passed parameters :
  34484. * - materialIndex (integer) : the index of the main mesh material.
  34485. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34486. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34487. * - mesh (Mesh) : the main mesh to create the submesh from.
  34488. * - renderingMesh (optional Mesh) : rendering mesh.
  34489. */
  34490. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34491. var minVertexIndex = Number.MAX_VALUE;
  34492. var maxVertexIndex = -Number.MAX_VALUE;
  34493. renderingMesh = (renderingMesh || mesh);
  34494. var indices = renderingMesh.getIndices();
  34495. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34496. var vertexIndex = indices[index];
  34497. if (vertexIndex < minVertexIndex)
  34498. minVertexIndex = vertexIndex;
  34499. if (vertexIndex > maxVertexIndex)
  34500. maxVertexIndex = vertexIndex;
  34501. }
  34502. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34503. };
  34504. return SubMesh;
  34505. }(BaseSubMesh));
  34506. BABYLON.SubMesh = SubMesh;
  34507. })(BABYLON || (BABYLON = {}));
  34508. //# sourceMappingURL=babylon.subMesh.js.map
  34509. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34510. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34511. s = arguments[i];
  34512. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34513. t[p] = s[p];
  34514. }
  34515. return t;
  34516. };
  34517. var BABYLON;
  34518. (function (BABYLON) {
  34519. /**
  34520. * Manages the defines for the Material
  34521. */
  34522. var MaterialDefines = /** @class */ (function () {
  34523. function MaterialDefines() {
  34524. this._isDirty = true;
  34525. /** @hidden */
  34526. this._areLightsDirty = true;
  34527. /** @hidden */
  34528. this._areAttributesDirty = true;
  34529. /** @hidden */
  34530. this._areTexturesDirty = true;
  34531. /** @hidden */
  34532. this._areFresnelDirty = true;
  34533. /** @hidden */
  34534. this._areMiscDirty = true;
  34535. /** @hidden */
  34536. this._areImageProcessingDirty = true;
  34537. /** @hidden */
  34538. this._normals = false;
  34539. /** @hidden */
  34540. this._uvs = false;
  34541. /** @hidden */
  34542. this._needNormals = false;
  34543. /** @hidden */
  34544. this._needUVs = false;
  34545. }
  34546. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34547. /**
  34548. * Specifies if the material needs to be re-calculated
  34549. */
  34550. get: function () {
  34551. return this._isDirty;
  34552. },
  34553. enumerable: true,
  34554. configurable: true
  34555. });
  34556. /**
  34557. * Marks the material to indicate that it has been re-calculated
  34558. */
  34559. MaterialDefines.prototype.markAsProcessed = function () {
  34560. this._isDirty = false;
  34561. this._areAttributesDirty = false;
  34562. this._areTexturesDirty = false;
  34563. this._areFresnelDirty = false;
  34564. this._areLightsDirty = false;
  34565. this._areMiscDirty = false;
  34566. this._areImageProcessingDirty = false;
  34567. };
  34568. /**
  34569. * Marks the material to indicate that it needs to be re-calculated
  34570. */
  34571. MaterialDefines.prototype.markAsUnprocessed = function () {
  34572. this._isDirty = true;
  34573. };
  34574. /**
  34575. * Marks the material to indicate all of its defines need to be re-calculated
  34576. */
  34577. MaterialDefines.prototype.markAllAsDirty = function () {
  34578. this._areTexturesDirty = true;
  34579. this._areAttributesDirty = true;
  34580. this._areLightsDirty = true;
  34581. this._areFresnelDirty = true;
  34582. this._areMiscDirty = true;
  34583. this._areImageProcessingDirty = true;
  34584. this._isDirty = true;
  34585. };
  34586. /**
  34587. * Marks the material to indicate that image processing needs to be re-calculated
  34588. */
  34589. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34590. this._areImageProcessingDirty = true;
  34591. this._isDirty = true;
  34592. };
  34593. /**
  34594. * Marks the material to indicate the lights need to be re-calculated
  34595. */
  34596. MaterialDefines.prototype.markAsLightDirty = function () {
  34597. this._areLightsDirty = true;
  34598. this._isDirty = true;
  34599. };
  34600. /**
  34601. * Marks the attribute state as changed
  34602. */
  34603. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34604. this._areAttributesDirty = true;
  34605. this._isDirty = true;
  34606. };
  34607. /**
  34608. * Marks the texture state as changed
  34609. */
  34610. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34611. this._areTexturesDirty = true;
  34612. this._isDirty = true;
  34613. };
  34614. /**
  34615. * Marks the fresnel state as changed
  34616. */
  34617. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34618. this._areFresnelDirty = true;
  34619. this._isDirty = true;
  34620. };
  34621. /**
  34622. * Marks the misc state as changed
  34623. */
  34624. MaterialDefines.prototype.markAsMiscDirty = function () {
  34625. this._areMiscDirty = true;
  34626. this._isDirty = true;
  34627. };
  34628. /**
  34629. * Rebuilds the material defines
  34630. */
  34631. MaterialDefines.prototype.rebuild = function () {
  34632. if (this._keys) {
  34633. delete this._keys;
  34634. }
  34635. this._keys = [];
  34636. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34637. var key = _a[_i];
  34638. if (key[0] === "_") {
  34639. continue;
  34640. }
  34641. this._keys.push(key);
  34642. }
  34643. };
  34644. /**
  34645. * Specifies if two material defines are equal
  34646. * @param other - A material define instance to compare to
  34647. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34648. */
  34649. MaterialDefines.prototype.isEqual = function (other) {
  34650. if (this._keys.length !== other._keys.length) {
  34651. return false;
  34652. }
  34653. for (var index = 0; index < this._keys.length; index++) {
  34654. var prop = this._keys[index];
  34655. if (this[prop] !== other[prop]) {
  34656. return false;
  34657. }
  34658. }
  34659. return true;
  34660. };
  34661. /**
  34662. * Clones this instance's defines to another instance
  34663. * @param other - material defines to clone values to
  34664. */
  34665. MaterialDefines.prototype.cloneTo = function (other) {
  34666. if (this._keys.length !== other._keys.length) {
  34667. other._keys = this._keys.slice(0);
  34668. }
  34669. for (var index = 0; index < this._keys.length; index++) {
  34670. var prop = this._keys[index];
  34671. other[prop] = this[prop];
  34672. }
  34673. };
  34674. /**
  34675. * Resets the material define values
  34676. */
  34677. MaterialDefines.prototype.reset = function () {
  34678. for (var index = 0; index < this._keys.length; index++) {
  34679. var prop = this._keys[index];
  34680. var type = typeof this[prop];
  34681. switch (type) {
  34682. case "number":
  34683. this[prop] = 0;
  34684. break;
  34685. case "string":
  34686. this[prop] = "";
  34687. break;
  34688. default:
  34689. this[prop] = false;
  34690. break;
  34691. }
  34692. }
  34693. };
  34694. /**
  34695. * Converts the material define values to a string
  34696. * @returns - String of material define information
  34697. */
  34698. MaterialDefines.prototype.toString = function () {
  34699. var result = "";
  34700. for (var index = 0; index < this._keys.length; index++) {
  34701. var prop = this._keys[index];
  34702. var value = this[prop];
  34703. var type = typeof value;
  34704. switch (type) {
  34705. case "number":
  34706. case "string":
  34707. result += "#define " + prop + " " + value + "\n";
  34708. break;
  34709. default:
  34710. if (value) {
  34711. result += "#define " + prop + "\n";
  34712. }
  34713. break;
  34714. }
  34715. }
  34716. return result;
  34717. };
  34718. return MaterialDefines;
  34719. }());
  34720. BABYLON.MaterialDefines = MaterialDefines;
  34721. /**
  34722. * Base class for the main features of a material in Babylon.js
  34723. */
  34724. var Material = /** @class */ (function () {
  34725. /**
  34726. * Creates a material instance
  34727. * @param name defines the name of the material
  34728. * @param scene defines the scene to reference
  34729. * @param doNotAdd specifies if the material should be added to the scene
  34730. */
  34731. function Material(name, scene, doNotAdd) {
  34732. /**
  34733. * Specifies if the ready state should be checked on each call
  34734. */
  34735. this.checkReadyOnEveryCall = false;
  34736. /**
  34737. * Specifies if the ready state should be checked once
  34738. */
  34739. this.checkReadyOnlyOnce = false;
  34740. /**
  34741. * The state of the material
  34742. */
  34743. this.state = "";
  34744. /**
  34745. * The alpha value of the material
  34746. */
  34747. this._alpha = 1.0;
  34748. /**
  34749. * Specifies if back face culling is enabled
  34750. */
  34751. this._backFaceCulling = true;
  34752. /**
  34753. * Specifies if the material should be serialized
  34754. */
  34755. this.doNotSerialize = false;
  34756. /**
  34757. * Specifies if the effect should be stored on sub meshes
  34758. */
  34759. this.storeEffectOnSubMeshes = false;
  34760. /**
  34761. * An event triggered when the material is disposed
  34762. */
  34763. this.onDisposeObservable = new BABYLON.Observable();
  34764. /**
  34765. * An event triggered when the material is bound
  34766. */
  34767. this.onBindObservable = new BABYLON.Observable();
  34768. /**
  34769. * An event triggered when the material is unbound
  34770. */
  34771. this.onUnBindObservable = new BABYLON.Observable();
  34772. /**
  34773. * Stores the value of the alpha mode
  34774. */
  34775. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34776. /**
  34777. * Stores the state of the need depth pre-pass value
  34778. */
  34779. this._needDepthPrePass = false;
  34780. /**
  34781. * Specifies if depth writing should be disabled
  34782. */
  34783. this.disableDepthWrite = false;
  34784. /**
  34785. * Specifies if depth writing should be forced
  34786. */
  34787. this.forceDepthWrite = false;
  34788. /**
  34789. * Specifies if there should be a separate pass for culling
  34790. */
  34791. this.separateCullingPass = false;
  34792. /**
  34793. * Stores the state specifing if fog should be enabled
  34794. */
  34795. this._fogEnabled = true;
  34796. /**
  34797. * Stores the size of points
  34798. */
  34799. this.pointSize = 1.0;
  34800. /**
  34801. * Stores the z offset value
  34802. */
  34803. this.zOffset = 0;
  34804. /**
  34805. * Specifies if the material was previously ready
  34806. */
  34807. this._wasPreviouslyReady = false;
  34808. /**
  34809. * Stores the fill mode state
  34810. */
  34811. this._fillMode = Material.TriangleFillMode;
  34812. this.name = name;
  34813. this.id = name || BABYLON.Tools.RandomId();
  34814. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34815. if (this._scene.useRightHandedSystem) {
  34816. this.sideOrientation = Material.ClockWiseSideOrientation;
  34817. }
  34818. else {
  34819. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34820. }
  34821. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34822. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34823. if (!doNotAdd) {
  34824. this._scene.materials.push(this);
  34825. }
  34826. }
  34827. Object.defineProperty(Material, "TriangleFillMode", {
  34828. /**
  34829. * Returns the triangle fill mode
  34830. */
  34831. get: function () {
  34832. return Material._TriangleFillMode;
  34833. },
  34834. enumerable: true,
  34835. configurable: true
  34836. });
  34837. Object.defineProperty(Material, "WireFrameFillMode", {
  34838. /**
  34839. * Returns the wireframe mode
  34840. */
  34841. get: function () {
  34842. return Material._WireFrameFillMode;
  34843. },
  34844. enumerable: true,
  34845. configurable: true
  34846. });
  34847. Object.defineProperty(Material, "PointFillMode", {
  34848. /**
  34849. * Returns the point fill mode
  34850. */
  34851. get: function () {
  34852. return Material._PointFillMode;
  34853. },
  34854. enumerable: true,
  34855. configurable: true
  34856. });
  34857. Object.defineProperty(Material, "PointListDrawMode", {
  34858. /**
  34859. * Returns the point list draw mode
  34860. */
  34861. get: function () {
  34862. return Material._PointListDrawMode;
  34863. },
  34864. enumerable: true,
  34865. configurable: true
  34866. });
  34867. Object.defineProperty(Material, "LineListDrawMode", {
  34868. /**
  34869. * Returns the line list draw mode
  34870. */
  34871. get: function () {
  34872. return Material._LineListDrawMode;
  34873. },
  34874. enumerable: true,
  34875. configurable: true
  34876. });
  34877. Object.defineProperty(Material, "LineLoopDrawMode", {
  34878. /**
  34879. * Returns the line loop draw mode
  34880. */
  34881. get: function () {
  34882. return Material._LineLoopDrawMode;
  34883. },
  34884. enumerable: true,
  34885. configurable: true
  34886. });
  34887. Object.defineProperty(Material, "LineStripDrawMode", {
  34888. /**
  34889. * Returns the line strip draw mode
  34890. */
  34891. get: function () {
  34892. return Material._LineStripDrawMode;
  34893. },
  34894. enumerable: true,
  34895. configurable: true
  34896. });
  34897. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34898. /**
  34899. * Returns the triangle strip draw mode
  34900. */
  34901. get: function () {
  34902. return Material._TriangleStripDrawMode;
  34903. },
  34904. enumerable: true,
  34905. configurable: true
  34906. });
  34907. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34908. /**
  34909. * Returns the triangle fan draw mode
  34910. */
  34911. get: function () {
  34912. return Material._TriangleFanDrawMode;
  34913. },
  34914. enumerable: true,
  34915. configurable: true
  34916. });
  34917. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34918. /**
  34919. * Returns the clock-wise side orientation
  34920. */
  34921. get: function () {
  34922. return Material._ClockWiseSideOrientation;
  34923. },
  34924. enumerable: true,
  34925. configurable: true
  34926. });
  34927. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34928. /**
  34929. * Returns the counter clock-wise side orientation
  34930. */
  34931. get: function () {
  34932. return Material._CounterClockWiseSideOrientation;
  34933. },
  34934. enumerable: true,
  34935. configurable: true
  34936. });
  34937. Object.defineProperty(Material, "TextureDirtyFlag", {
  34938. /**
  34939. * Returns the dirty texture flag value
  34940. */
  34941. get: function () {
  34942. return Material._TextureDirtyFlag;
  34943. },
  34944. enumerable: true,
  34945. configurable: true
  34946. });
  34947. Object.defineProperty(Material, "LightDirtyFlag", {
  34948. /**
  34949. * Returns the dirty light flag value
  34950. */
  34951. get: function () {
  34952. return Material._LightDirtyFlag;
  34953. },
  34954. enumerable: true,
  34955. configurable: true
  34956. });
  34957. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34958. /**
  34959. * Returns the dirty fresnel flag value
  34960. */
  34961. get: function () {
  34962. return Material._FresnelDirtyFlag;
  34963. },
  34964. enumerable: true,
  34965. configurable: true
  34966. });
  34967. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34968. /**
  34969. * Returns the dirty attributes flag value
  34970. */
  34971. get: function () {
  34972. return Material._AttributesDirtyFlag;
  34973. },
  34974. enumerable: true,
  34975. configurable: true
  34976. });
  34977. Object.defineProperty(Material, "MiscDirtyFlag", {
  34978. /**
  34979. * Returns the dirty misc flag value
  34980. */
  34981. get: function () {
  34982. return Material._MiscDirtyFlag;
  34983. },
  34984. enumerable: true,
  34985. configurable: true
  34986. });
  34987. Object.defineProperty(Material.prototype, "alpha", {
  34988. /**
  34989. * Gets the alpha value of the material
  34990. */
  34991. get: function () {
  34992. return this._alpha;
  34993. },
  34994. /**
  34995. * Sets the alpha value of the material
  34996. */
  34997. set: function (value) {
  34998. if (this._alpha === value) {
  34999. return;
  35000. }
  35001. this._alpha = value;
  35002. this.markAsDirty(Material.MiscDirtyFlag);
  35003. },
  35004. enumerable: true,
  35005. configurable: true
  35006. });
  35007. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35008. /**
  35009. * Gets the back-face culling state
  35010. */
  35011. get: function () {
  35012. return this._backFaceCulling;
  35013. },
  35014. /**
  35015. * Sets the back-face culling state
  35016. */
  35017. set: function (value) {
  35018. if (this._backFaceCulling === value) {
  35019. return;
  35020. }
  35021. this._backFaceCulling = value;
  35022. this.markAsDirty(Material.TextureDirtyFlag);
  35023. },
  35024. enumerable: true,
  35025. configurable: true
  35026. });
  35027. Object.defineProperty(Material.prototype, "onDispose", {
  35028. /**
  35029. * Called during a dispose event
  35030. */
  35031. set: function (callback) {
  35032. if (this._onDisposeObserver) {
  35033. this.onDisposeObservable.remove(this._onDisposeObserver);
  35034. }
  35035. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35036. },
  35037. enumerable: true,
  35038. configurable: true
  35039. });
  35040. Object.defineProperty(Material.prototype, "onBind", {
  35041. /**
  35042. * Called during a bind event
  35043. */
  35044. set: function (callback) {
  35045. if (this._onBindObserver) {
  35046. this.onBindObservable.remove(this._onBindObserver);
  35047. }
  35048. this._onBindObserver = this.onBindObservable.add(callback);
  35049. },
  35050. enumerable: true,
  35051. configurable: true
  35052. });
  35053. Object.defineProperty(Material.prototype, "alphaMode", {
  35054. /**
  35055. * Gets the value of the alpha mode
  35056. */
  35057. get: function () {
  35058. return this._alphaMode;
  35059. },
  35060. /**
  35061. * Sets the value of the alpha mode.
  35062. *
  35063. * | Value | Type | Description |
  35064. * | --- | --- | --- |
  35065. * | 0 | ALPHA_DISABLE | |
  35066. * | 1 | ALPHA_ADD | |
  35067. * | 2 | ALPHA_COMBINE | |
  35068. * | 3 | ALPHA_SUBTRACT | |
  35069. * | 4 | ALPHA_MULTIPLY | |
  35070. * | 5 | ALPHA_MAXIMIZED | |
  35071. * | 6 | ALPHA_ONEONE | |
  35072. * | 7 | ALPHA_PREMULTIPLIED | |
  35073. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35074. * | 9 | ALPHA_INTERPOLATE | |
  35075. * | 10 | ALPHA_SCREENMODE | |
  35076. *
  35077. */
  35078. set: function (value) {
  35079. if (this._alphaMode === value) {
  35080. return;
  35081. }
  35082. this._alphaMode = value;
  35083. this.markAsDirty(Material.TextureDirtyFlag);
  35084. },
  35085. enumerable: true,
  35086. configurable: true
  35087. });
  35088. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35089. /**
  35090. * Gets the depth pre-pass value
  35091. */
  35092. get: function () {
  35093. return this._needDepthPrePass;
  35094. },
  35095. /**
  35096. * Sets the need depth pre-pass value
  35097. */
  35098. set: function (value) {
  35099. if (this._needDepthPrePass === value) {
  35100. return;
  35101. }
  35102. this._needDepthPrePass = value;
  35103. if (this._needDepthPrePass) {
  35104. this.checkReadyOnEveryCall = true;
  35105. }
  35106. },
  35107. enumerable: true,
  35108. configurable: true
  35109. });
  35110. Object.defineProperty(Material.prototype, "fogEnabled", {
  35111. /**
  35112. * Gets the value of the fog enabled state
  35113. */
  35114. get: function () {
  35115. return this._fogEnabled;
  35116. },
  35117. /**
  35118. * Sets the state for enabling fog
  35119. */
  35120. set: function (value) {
  35121. if (this._fogEnabled === value) {
  35122. return;
  35123. }
  35124. this._fogEnabled = value;
  35125. this.markAsDirty(Material.MiscDirtyFlag);
  35126. },
  35127. enumerable: true,
  35128. configurable: true
  35129. });
  35130. Object.defineProperty(Material.prototype, "wireframe", {
  35131. /**
  35132. * Gets a value specifying if wireframe mode is enabled
  35133. */
  35134. get: function () {
  35135. switch (this._fillMode) {
  35136. case Material.WireFrameFillMode:
  35137. case Material.LineListDrawMode:
  35138. case Material.LineLoopDrawMode:
  35139. case Material.LineStripDrawMode:
  35140. return true;
  35141. }
  35142. return this._scene.forceWireframe;
  35143. },
  35144. /**
  35145. * Sets the state of wireframe mode
  35146. */
  35147. set: function (value) {
  35148. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35149. },
  35150. enumerable: true,
  35151. configurable: true
  35152. });
  35153. Object.defineProperty(Material.prototype, "pointsCloud", {
  35154. /**
  35155. * Gets the value specifying if point clouds are enabled
  35156. */
  35157. get: function () {
  35158. switch (this._fillMode) {
  35159. case Material.PointFillMode:
  35160. case Material.PointListDrawMode:
  35161. return true;
  35162. }
  35163. return this._scene.forcePointsCloud;
  35164. },
  35165. /**
  35166. * Sets the state of point cloud mode
  35167. */
  35168. set: function (value) {
  35169. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35170. },
  35171. enumerable: true,
  35172. configurable: true
  35173. });
  35174. Object.defineProperty(Material.prototype, "fillMode", {
  35175. /**
  35176. * Gets the material fill mode
  35177. */
  35178. get: function () {
  35179. return this._fillMode;
  35180. },
  35181. /**
  35182. * Sets the material fill mode
  35183. */
  35184. set: function (value) {
  35185. if (this._fillMode === value) {
  35186. return;
  35187. }
  35188. this._fillMode = value;
  35189. this.markAsDirty(Material.MiscDirtyFlag);
  35190. },
  35191. enumerable: true,
  35192. configurable: true
  35193. });
  35194. /**
  35195. * Returns a string representation of the current material
  35196. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35197. * @returns a string with material information
  35198. */
  35199. Material.prototype.toString = function (fullDetails) {
  35200. var ret = "Name: " + this.name;
  35201. if (fullDetails) {
  35202. }
  35203. return ret;
  35204. };
  35205. /**
  35206. * Gets the class name of the material
  35207. * @returns a string with the class name of the material
  35208. */
  35209. Material.prototype.getClassName = function () {
  35210. return "Material";
  35211. };
  35212. Object.defineProperty(Material.prototype, "isFrozen", {
  35213. /**
  35214. * Specifies if updates for the material been locked
  35215. */
  35216. get: function () {
  35217. return this.checkReadyOnlyOnce;
  35218. },
  35219. enumerable: true,
  35220. configurable: true
  35221. });
  35222. /**
  35223. * Locks updates for the material
  35224. */
  35225. Material.prototype.freeze = function () {
  35226. this.checkReadyOnlyOnce = true;
  35227. };
  35228. /**
  35229. * Unlocks updates for the material
  35230. */
  35231. Material.prototype.unfreeze = function () {
  35232. this.checkReadyOnlyOnce = false;
  35233. };
  35234. /**
  35235. * Specifies if the material is ready to be used
  35236. * @param mesh defines the mesh to check
  35237. * @param useInstances specifies if instances should be used
  35238. * @returns a boolean indicating if the material is ready to be used
  35239. */
  35240. Material.prototype.isReady = function (mesh, useInstances) {
  35241. return true;
  35242. };
  35243. /**
  35244. * Specifies that the submesh is ready to be used
  35245. * @param mesh defines the mesh to check
  35246. * @param subMesh defines which submesh to check
  35247. * @param useInstances specifies that instances should be used
  35248. * @returns a boolean indicating that the submesh is ready or not
  35249. */
  35250. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35251. return false;
  35252. };
  35253. /**
  35254. * Returns the material effect
  35255. * @returns the effect associated with the material
  35256. */
  35257. Material.prototype.getEffect = function () {
  35258. return this._effect;
  35259. };
  35260. /**
  35261. * Returns the current scene
  35262. * @returns a Scene
  35263. */
  35264. Material.prototype.getScene = function () {
  35265. return this._scene;
  35266. };
  35267. /**
  35268. * Specifies if the material will require alpha blending
  35269. * @returns a boolean specifying if alpha blending is needed
  35270. */
  35271. Material.prototype.needAlphaBlending = function () {
  35272. return (this.alpha < 1.0);
  35273. };
  35274. /**
  35275. * Specifies if the mesh will require alpha blending
  35276. * @param mesh defines the mesh to check
  35277. * @returns a boolean specifying if alpha blending is needed for the mesh
  35278. */
  35279. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35280. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35281. };
  35282. /**
  35283. * Specifies if this material should be rendered in alpha test mode
  35284. * @returns a boolean specifying if an alpha test is needed.
  35285. */
  35286. Material.prototype.needAlphaTesting = function () {
  35287. return false;
  35288. };
  35289. /**
  35290. * Gets the texture used for the alpha test
  35291. * @returns the texture to use for alpha testing
  35292. */
  35293. Material.prototype.getAlphaTestTexture = function () {
  35294. return null;
  35295. };
  35296. /**
  35297. * Marks the material to indicate that it needs to be re-calculated
  35298. */
  35299. Material.prototype.markDirty = function () {
  35300. this._wasPreviouslyReady = false;
  35301. };
  35302. /** @hidden */
  35303. Material.prototype._preBind = function (effect, overrideOrientation) {
  35304. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35305. var engine = this._scene.getEngine();
  35306. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35307. var reverse = orientation === Material.ClockWiseSideOrientation;
  35308. engine.enableEffect(effect ? effect : this._effect);
  35309. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35310. return reverse;
  35311. };
  35312. /**
  35313. * Binds the material to the mesh
  35314. * @param world defines the world transformation matrix
  35315. * @param mesh defines the mesh to bind the material to
  35316. */
  35317. Material.prototype.bind = function (world, mesh) {
  35318. };
  35319. /**
  35320. * Binds the submesh to the material
  35321. * @param world defines the world transformation matrix
  35322. * @param mesh defines the mesh containing the submesh
  35323. * @param subMesh defines the submesh to bind the material to
  35324. */
  35325. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35326. };
  35327. /**
  35328. * Binds the world matrix to the material
  35329. * @param world defines the world transformation matrix
  35330. */
  35331. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35332. };
  35333. /**
  35334. * Binds the scene's uniform buffer to the effect.
  35335. * @param effect defines the effect to bind to the scene uniform buffer
  35336. * @param sceneUbo defines the uniform buffer storing scene data
  35337. */
  35338. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35339. sceneUbo.bindToEffect(effect, "Scene");
  35340. };
  35341. /**
  35342. * Binds the view matrix to the effect
  35343. * @param effect defines the effect to bind the view matrix to
  35344. */
  35345. Material.prototype.bindView = function (effect) {
  35346. if (!this._useUBO) {
  35347. effect.setMatrix("view", this.getScene().getViewMatrix());
  35348. }
  35349. else {
  35350. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35351. }
  35352. };
  35353. /**
  35354. * Binds the view projection matrix to the effect
  35355. * @param effect defines the effect to bind the view projection matrix to
  35356. */
  35357. Material.prototype.bindViewProjection = function (effect) {
  35358. if (!this._useUBO) {
  35359. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35360. }
  35361. else {
  35362. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35363. }
  35364. };
  35365. /**
  35366. * Specifies if material alpha testing should be turned on for the mesh
  35367. * @param mesh defines the mesh to check
  35368. */
  35369. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35370. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35371. };
  35372. /**
  35373. * Processes to execute after binding the material to a mesh
  35374. * @param mesh defines the rendered mesh
  35375. */
  35376. Material.prototype._afterBind = function (mesh) {
  35377. this._scene._cachedMaterial = this;
  35378. if (mesh) {
  35379. this._scene._cachedVisibility = mesh.visibility;
  35380. }
  35381. else {
  35382. this._scene._cachedVisibility = 1;
  35383. }
  35384. if (mesh) {
  35385. this.onBindObservable.notifyObservers(mesh);
  35386. }
  35387. if (this.disableDepthWrite) {
  35388. var engine = this._scene.getEngine();
  35389. this._cachedDepthWriteState = engine.getDepthWrite();
  35390. engine.setDepthWrite(false);
  35391. }
  35392. };
  35393. /**
  35394. * Unbinds the material from the mesh
  35395. */
  35396. Material.prototype.unbind = function () {
  35397. this.onUnBindObservable.notifyObservers(this);
  35398. if (this.disableDepthWrite) {
  35399. var engine = this._scene.getEngine();
  35400. engine.setDepthWrite(this._cachedDepthWriteState);
  35401. }
  35402. };
  35403. /**
  35404. * Gets the active textures from the material
  35405. * @returns an array of textures
  35406. */
  35407. Material.prototype.getActiveTextures = function () {
  35408. return [];
  35409. };
  35410. /**
  35411. * Specifies if the material uses a texture
  35412. * @param texture defines the texture to check against the material
  35413. * @returns a boolean specifying if the material uses the texture
  35414. */
  35415. Material.prototype.hasTexture = function (texture) {
  35416. return false;
  35417. };
  35418. /**
  35419. * Makes a duplicate of the material, and gives it a new name
  35420. * @param name defines the new name for the duplicated material
  35421. * @returns the cloned material
  35422. */
  35423. Material.prototype.clone = function (name) {
  35424. return null;
  35425. };
  35426. /**
  35427. * Gets the meshes bound to the material
  35428. * @returns an array of meshes bound to the material
  35429. */
  35430. Material.prototype.getBindedMeshes = function () {
  35431. var result = new Array();
  35432. for (var index = 0; index < this._scene.meshes.length; index++) {
  35433. var mesh = this._scene.meshes[index];
  35434. if (mesh.material === this) {
  35435. result.push(mesh);
  35436. }
  35437. }
  35438. return result;
  35439. };
  35440. /**
  35441. * Force shader compilation
  35442. * @param mesh defines the mesh associated with this material
  35443. * @param onCompiled defines a function to execute once the material is compiled
  35444. * @param options defines the options to configure the compilation
  35445. */
  35446. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35447. var _this = this;
  35448. var localOptions = __assign({ clipPlane: false }, options);
  35449. var subMesh = new BABYLON.BaseSubMesh();
  35450. var scene = this.getScene();
  35451. var checkReady = function () {
  35452. if (!_this._scene || !_this._scene.getEngine()) {
  35453. return;
  35454. }
  35455. if (subMesh._materialDefines) {
  35456. subMesh._materialDefines._renderId = -1;
  35457. }
  35458. var clipPlaneState = scene.clipPlane;
  35459. if (localOptions.clipPlane) {
  35460. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35461. }
  35462. if (_this.storeEffectOnSubMeshes) {
  35463. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35464. if (onCompiled) {
  35465. onCompiled(_this);
  35466. }
  35467. }
  35468. else {
  35469. setTimeout(checkReady, 16);
  35470. }
  35471. }
  35472. else {
  35473. if (_this.isReady(mesh)) {
  35474. if (onCompiled) {
  35475. onCompiled(_this);
  35476. }
  35477. }
  35478. else {
  35479. setTimeout(checkReady, 16);
  35480. }
  35481. }
  35482. if (localOptions.clipPlane) {
  35483. scene.clipPlane = clipPlaneState;
  35484. }
  35485. };
  35486. checkReady();
  35487. };
  35488. /**
  35489. * Force shader compilation
  35490. * @param mesh defines the mesh that will use this material
  35491. * @param options defines additional options for compiling the shaders
  35492. * @returns a promise that resolves when the compilation completes
  35493. */
  35494. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35495. var _this = this;
  35496. return new Promise(function (resolve) {
  35497. _this.forceCompilation(mesh, function () {
  35498. resolve();
  35499. }, options);
  35500. });
  35501. };
  35502. /**
  35503. * Marks a define in the material to indicate that it needs to be re-computed
  35504. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35505. */
  35506. Material.prototype.markAsDirty = function (flag) {
  35507. if (flag & Material.TextureDirtyFlag) {
  35508. this._markAllSubMeshesAsTexturesDirty();
  35509. }
  35510. if (flag & Material.LightDirtyFlag) {
  35511. this._markAllSubMeshesAsLightsDirty();
  35512. }
  35513. if (flag & Material.FresnelDirtyFlag) {
  35514. this._markAllSubMeshesAsFresnelDirty();
  35515. }
  35516. if (flag & Material.AttributesDirtyFlag) {
  35517. this._markAllSubMeshesAsAttributesDirty();
  35518. }
  35519. if (flag & Material.MiscDirtyFlag) {
  35520. this._markAllSubMeshesAsMiscDirty();
  35521. }
  35522. this.getScene().resetCachedMaterial();
  35523. };
  35524. /**
  35525. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35526. * @param func defines a function which checks material defines against the submeshes
  35527. */
  35528. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35529. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35530. var mesh = _a[_i];
  35531. if (!mesh.subMeshes) {
  35532. continue;
  35533. }
  35534. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35535. var subMesh = _c[_b];
  35536. if (subMesh.getMaterial() !== this) {
  35537. continue;
  35538. }
  35539. if (!subMesh._materialDefines) {
  35540. continue;
  35541. }
  35542. func(subMesh._materialDefines);
  35543. }
  35544. }
  35545. };
  35546. /**
  35547. * Indicates that image processing needs to be re-calculated for all submeshes
  35548. */
  35549. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35550. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35551. };
  35552. /**
  35553. * Indicates that textures need to be re-calculated for all submeshes
  35554. */
  35555. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35556. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35557. };
  35558. /**
  35559. * Indicates that fresnel needs to be re-calculated for all submeshes
  35560. */
  35561. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35562. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35563. };
  35564. /**
  35565. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35566. */
  35567. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35568. this._markAllSubMeshesAsDirty(function (defines) {
  35569. defines.markAsFresnelDirty();
  35570. defines.markAsMiscDirty();
  35571. });
  35572. };
  35573. /**
  35574. * Indicates that lights need to be re-calculated for all submeshes
  35575. */
  35576. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35577. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35578. };
  35579. /**
  35580. * Indicates that attributes need to be re-calculated for all submeshes
  35581. */
  35582. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35583. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35584. };
  35585. /**
  35586. * Indicates that misc needs to be re-calculated for all submeshes
  35587. */
  35588. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35589. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35590. };
  35591. /**
  35592. * Indicates that textures and misc need to be re-calculated for all submeshes
  35593. */
  35594. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35595. this._markAllSubMeshesAsDirty(function (defines) {
  35596. defines.markAsTexturesDirty();
  35597. defines.markAsMiscDirty();
  35598. });
  35599. };
  35600. /**
  35601. * Disposes the material
  35602. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35603. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35604. */
  35605. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35606. // Animations
  35607. this.getScene().stopAnimation(this);
  35608. this.getScene().freeProcessedMaterials();
  35609. // Remove from scene
  35610. var index = this._scene.materials.indexOf(this);
  35611. if (index >= 0) {
  35612. this._scene.materials.splice(index, 1);
  35613. }
  35614. // Remove from meshes
  35615. for (index = 0; index < this._scene.meshes.length; index++) {
  35616. var mesh = this._scene.meshes[index];
  35617. if (mesh.material === this) {
  35618. mesh.material = null;
  35619. if (mesh.geometry) {
  35620. var geometry = (mesh.geometry);
  35621. if (this.storeEffectOnSubMeshes) {
  35622. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35623. var subMesh = _a[_i];
  35624. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35625. if (forceDisposeEffect && subMesh._materialEffect) {
  35626. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35627. }
  35628. }
  35629. }
  35630. else {
  35631. geometry._releaseVertexArrayObject(this._effect);
  35632. }
  35633. }
  35634. }
  35635. }
  35636. this._uniformBuffer.dispose();
  35637. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35638. if (forceDisposeEffect && this._effect) {
  35639. if (!this.storeEffectOnSubMeshes) {
  35640. this._scene.getEngine()._releaseEffect(this._effect);
  35641. }
  35642. this._effect = null;
  35643. }
  35644. // Callback
  35645. this.onDisposeObservable.notifyObservers(this);
  35646. this.onDisposeObservable.clear();
  35647. this.onBindObservable.clear();
  35648. this.onUnBindObservable.clear();
  35649. };
  35650. /**
  35651. * Serializes this material
  35652. * @returns the serialized material object
  35653. */
  35654. Material.prototype.serialize = function () {
  35655. return BABYLON.SerializationHelper.Serialize(this);
  35656. };
  35657. /**
  35658. * Creates a MultiMaterial from parsed MultiMaterial data.
  35659. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35660. * @param scene defines the hosting scene
  35661. * @returns a new MultiMaterial
  35662. */
  35663. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35664. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35665. multiMaterial.id = parsedMultiMaterial.id;
  35666. if (BABYLON.Tags) {
  35667. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35668. }
  35669. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35670. var subMatId = parsedMultiMaterial.materials[matIndex];
  35671. if (subMatId) {
  35672. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35673. }
  35674. else {
  35675. multiMaterial.subMaterials.push(null);
  35676. }
  35677. }
  35678. return multiMaterial;
  35679. };
  35680. /**
  35681. * Creates a material from parsed material data
  35682. * @param parsedMaterial defines parsed material data
  35683. * @param scene defines the hosting scene
  35684. * @param rootUrl defines the root URL to use to load textures
  35685. * @returns a new material
  35686. */
  35687. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35688. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35689. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35690. }
  35691. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35692. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35693. if (!BABYLON.LegacyPBRMaterial) {
  35694. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35695. return;
  35696. }
  35697. }
  35698. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35699. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35700. };
  35701. // Triangle views
  35702. Material._TriangleFillMode = 0;
  35703. Material._WireFrameFillMode = 1;
  35704. Material._PointFillMode = 2;
  35705. // Draw modes
  35706. Material._PointListDrawMode = 3;
  35707. Material._LineListDrawMode = 4;
  35708. Material._LineLoopDrawMode = 5;
  35709. Material._LineStripDrawMode = 6;
  35710. Material._TriangleStripDrawMode = 7;
  35711. Material._TriangleFanDrawMode = 8;
  35712. /**
  35713. * Stores the clock-wise side orientation
  35714. */
  35715. Material._ClockWiseSideOrientation = 0;
  35716. /**
  35717. * Stores the counter clock-wise side orientation
  35718. */
  35719. Material._CounterClockWiseSideOrientation = 1;
  35720. /**
  35721. * The dirty texture flag value
  35722. */
  35723. Material._TextureDirtyFlag = 1;
  35724. /**
  35725. * The dirty light flag value
  35726. */
  35727. Material._LightDirtyFlag = 2;
  35728. /**
  35729. * The dirty fresnel flag value
  35730. */
  35731. Material._FresnelDirtyFlag = 4;
  35732. /**
  35733. * The dirty attribute flag value
  35734. */
  35735. Material._AttributesDirtyFlag = 8;
  35736. /**
  35737. * The dirty misc flag value
  35738. */
  35739. Material._MiscDirtyFlag = 16;
  35740. __decorate([
  35741. BABYLON.serialize()
  35742. ], Material.prototype, "id", void 0);
  35743. __decorate([
  35744. BABYLON.serialize()
  35745. ], Material.prototype, "name", void 0);
  35746. __decorate([
  35747. BABYLON.serialize()
  35748. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35749. __decorate([
  35750. BABYLON.serialize()
  35751. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35752. __decorate([
  35753. BABYLON.serialize()
  35754. ], Material.prototype, "state", void 0);
  35755. __decorate([
  35756. BABYLON.serialize("alpha")
  35757. ], Material.prototype, "_alpha", void 0);
  35758. __decorate([
  35759. BABYLON.serialize("backFaceCulling")
  35760. ], Material.prototype, "_backFaceCulling", void 0);
  35761. __decorate([
  35762. BABYLON.serialize()
  35763. ], Material.prototype, "sideOrientation", void 0);
  35764. __decorate([
  35765. BABYLON.serialize("alphaMode")
  35766. ], Material.prototype, "_alphaMode", void 0);
  35767. __decorate([
  35768. BABYLON.serialize()
  35769. ], Material.prototype, "_needDepthPrePass", void 0);
  35770. __decorate([
  35771. BABYLON.serialize()
  35772. ], Material.prototype, "disableDepthWrite", void 0);
  35773. __decorate([
  35774. BABYLON.serialize()
  35775. ], Material.prototype, "forceDepthWrite", void 0);
  35776. __decorate([
  35777. BABYLON.serialize()
  35778. ], Material.prototype, "separateCullingPass", void 0);
  35779. __decorate([
  35780. BABYLON.serialize("fogEnabled")
  35781. ], Material.prototype, "_fogEnabled", void 0);
  35782. __decorate([
  35783. BABYLON.serialize()
  35784. ], Material.prototype, "pointSize", void 0);
  35785. __decorate([
  35786. BABYLON.serialize()
  35787. ], Material.prototype, "zOffset", void 0);
  35788. __decorate([
  35789. BABYLON.serialize()
  35790. ], Material.prototype, "wireframe", null);
  35791. __decorate([
  35792. BABYLON.serialize()
  35793. ], Material.prototype, "pointsCloud", null);
  35794. __decorate([
  35795. BABYLON.serialize()
  35796. ], Material.prototype, "fillMode", null);
  35797. return Material;
  35798. }());
  35799. BABYLON.Material = Material;
  35800. })(BABYLON || (BABYLON = {}));
  35801. //# sourceMappingURL=babylon.material.js.map
  35802. var BABYLON;
  35803. (function (BABYLON) {
  35804. var UniformBuffer = /** @class */ (function () {
  35805. /**
  35806. * Uniform buffer objects.
  35807. *
  35808. * Handles blocks of uniform on the GPU.
  35809. *
  35810. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35811. *
  35812. * For more information, please refer to :
  35813. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35814. */
  35815. function UniformBuffer(engine, data, dynamic) {
  35816. this._engine = engine;
  35817. this._noUBO = !engine.supportsUniformBuffers;
  35818. this._dynamic = dynamic;
  35819. this._data = data || [];
  35820. this._uniformLocations = {};
  35821. this._uniformSizes = {};
  35822. this._uniformLocationPointer = 0;
  35823. this._needSync = false;
  35824. if (this._noUBO) {
  35825. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35826. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35827. this.updateFloat = this._updateFloatForEffect;
  35828. this.updateFloat2 = this._updateFloat2ForEffect;
  35829. this.updateFloat3 = this._updateFloat3ForEffect;
  35830. this.updateFloat4 = this._updateFloat4ForEffect;
  35831. this.updateMatrix = this._updateMatrixForEffect;
  35832. this.updateVector3 = this._updateVector3ForEffect;
  35833. this.updateVector4 = this._updateVector4ForEffect;
  35834. this.updateColor3 = this._updateColor3ForEffect;
  35835. this.updateColor4 = this._updateColor4ForEffect;
  35836. }
  35837. else {
  35838. this._engine._uniformBuffers.push(this);
  35839. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35840. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35841. this.updateFloat = this._updateFloatForUniform;
  35842. this.updateFloat2 = this._updateFloat2ForUniform;
  35843. this.updateFloat3 = this._updateFloat3ForUniform;
  35844. this.updateFloat4 = this._updateFloat4ForUniform;
  35845. this.updateMatrix = this._updateMatrixForUniform;
  35846. this.updateVector3 = this._updateVector3ForUniform;
  35847. this.updateVector4 = this._updateVector4ForUniform;
  35848. this.updateColor3 = this._updateColor3ForUniform;
  35849. this.updateColor4 = this._updateColor4ForUniform;
  35850. }
  35851. }
  35852. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35853. // Properties
  35854. /**
  35855. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35856. * or just falling back on setUniformXXX calls.
  35857. */
  35858. get: function () {
  35859. return !this._noUBO;
  35860. },
  35861. enumerable: true,
  35862. configurable: true
  35863. });
  35864. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35865. /**
  35866. * Indicates if the WebGL underlying uniform buffer is in sync
  35867. * with the javascript cache data.
  35868. */
  35869. get: function () {
  35870. return !this._needSync;
  35871. },
  35872. enumerable: true,
  35873. configurable: true
  35874. });
  35875. /**
  35876. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35877. * Also, a dynamic UniformBuffer will disable cache verification and always
  35878. * update the underlying WebGL uniform buffer to the GPU.
  35879. */
  35880. UniformBuffer.prototype.isDynamic = function () {
  35881. return this._dynamic !== undefined;
  35882. };
  35883. /**
  35884. * The data cache on JS side.
  35885. */
  35886. UniformBuffer.prototype.getData = function () {
  35887. return this._bufferData;
  35888. };
  35889. /**
  35890. * The underlying WebGL Uniform buffer.
  35891. */
  35892. UniformBuffer.prototype.getBuffer = function () {
  35893. return this._buffer;
  35894. };
  35895. /**
  35896. * std140 layout specifies how to align data within an UBO structure.
  35897. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35898. * for specs.
  35899. */
  35900. UniformBuffer.prototype._fillAlignment = function (size) {
  35901. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35902. // and 4x4 matrices
  35903. // TODO : change if other types are used
  35904. var alignment;
  35905. if (size <= 2) {
  35906. alignment = size;
  35907. }
  35908. else {
  35909. alignment = 4;
  35910. }
  35911. if ((this._uniformLocationPointer % alignment) !== 0) {
  35912. var oldPointer = this._uniformLocationPointer;
  35913. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35914. var diff = this._uniformLocationPointer - oldPointer;
  35915. for (var i = 0; i < diff; i++) {
  35916. this._data.push(0);
  35917. }
  35918. }
  35919. };
  35920. /**
  35921. * Adds an uniform in the buffer.
  35922. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35923. * for the layout to be correct !
  35924. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35925. * @param {number|number[]} size Data size, or data directly.
  35926. */
  35927. UniformBuffer.prototype.addUniform = function (name, size) {
  35928. if (this._noUBO) {
  35929. return;
  35930. }
  35931. if (this._uniformLocations[name] !== undefined) {
  35932. // Already existing uniform
  35933. return;
  35934. }
  35935. // This function must be called in the order of the shader layout !
  35936. // size can be the size of the uniform, or data directly
  35937. var data;
  35938. if (size instanceof Array) {
  35939. data = size;
  35940. size = data.length;
  35941. }
  35942. else {
  35943. size = size;
  35944. data = [];
  35945. // Fill with zeros
  35946. for (var i = 0; i < size; i++) {
  35947. data.push(0);
  35948. }
  35949. }
  35950. this._fillAlignment(size);
  35951. this._uniformSizes[name] = size;
  35952. this._uniformLocations[name] = this._uniformLocationPointer;
  35953. this._uniformLocationPointer += size;
  35954. for (var i = 0; i < size; i++) {
  35955. this._data.push(data[i]);
  35956. }
  35957. this._needSync = true;
  35958. };
  35959. /**
  35960. * Wrapper for addUniform.
  35961. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35962. * @param {Matrix} mat A 4x4 matrix.
  35963. */
  35964. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35965. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35966. };
  35967. /**
  35968. * Wrapper for addUniform.
  35969. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35970. * @param {number} x
  35971. * @param {number} y
  35972. */
  35973. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35974. var temp = [x, y];
  35975. this.addUniform(name, temp);
  35976. };
  35977. /**
  35978. * Wrapper for addUniform.
  35979. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35980. * @param {number} x
  35981. * @param {number} y
  35982. * @param {number} z
  35983. */
  35984. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35985. var temp = [x, y, z];
  35986. this.addUniform(name, temp);
  35987. };
  35988. /**
  35989. * Wrapper for addUniform.
  35990. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35991. * @param {Color3} color
  35992. */
  35993. UniformBuffer.prototype.addColor3 = function (name, color) {
  35994. var temp = new Array();
  35995. color.toArray(temp);
  35996. this.addUniform(name, temp);
  35997. };
  35998. /**
  35999. * Wrapper for addUniform.
  36000. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36001. * @param {Color3} color
  36002. * @param {number} alpha
  36003. */
  36004. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36005. var temp = new Array();
  36006. color.toArray(temp);
  36007. temp.push(alpha);
  36008. this.addUniform(name, temp);
  36009. };
  36010. /**
  36011. * Wrapper for addUniform.
  36012. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36013. * @param {Vector3} vector
  36014. */
  36015. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36016. var temp = new Array();
  36017. vector.toArray(temp);
  36018. this.addUniform(name, temp);
  36019. };
  36020. /**
  36021. * Wrapper for addUniform.
  36022. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36023. */
  36024. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36025. this.addUniform(name, 12);
  36026. };
  36027. /**
  36028. * Wrapper for addUniform.
  36029. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36030. */
  36031. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36032. this.addUniform(name, 8);
  36033. };
  36034. /**
  36035. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36036. */
  36037. UniformBuffer.prototype.create = function () {
  36038. if (this._noUBO) {
  36039. return;
  36040. }
  36041. if (this._buffer) {
  36042. return; // nothing to do
  36043. }
  36044. // See spec, alignment must be filled as a vec4
  36045. this._fillAlignment(4);
  36046. this._bufferData = new Float32Array(this._data);
  36047. this._rebuild();
  36048. this._needSync = true;
  36049. };
  36050. UniformBuffer.prototype._rebuild = function () {
  36051. if (this._noUBO) {
  36052. return;
  36053. }
  36054. if (this._dynamic) {
  36055. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36056. }
  36057. else {
  36058. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36059. }
  36060. };
  36061. /**
  36062. * Updates the WebGL Uniform Buffer on the GPU.
  36063. * If the `dynamic` flag is set to true, no cache comparison is done.
  36064. * Otherwise, the buffer will be updated only if the cache differs.
  36065. */
  36066. UniformBuffer.prototype.update = function () {
  36067. if (!this._buffer) {
  36068. this.create();
  36069. return;
  36070. }
  36071. if (!this._dynamic && !this._needSync) {
  36072. return;
  36073. }
  36074. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36075. this._needSync = false;
  36076. };
  36077. /**
  36078. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36079. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36080. * @param {number[]|Float32Array} data Flattened data
  36081. * @param {number} size Size of the data.
  36082. */
  36083. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36084. var location = this._uniformLocations[uniformName];
  36085. if (location === undefined) {
  36086. if (this._buffer) {
  36087. // Cannot add an uniform if the buffer is already created
  36088. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36089. return;
  36090. }
  36091. this.addUniform(uniformName, size);
  36092. location = this._uniformLocations[uniformName];
  36093. }
  36094. if (!this._buffer) {
  36095. this.create();
  36096. }
  36097. if (!this._dynamic) {
  36098. // Cache for static uniform buffers
  36099. var changed = false;
  36100. for (var i = 0; i < size; i++) {
  36101. if (this._bufferData[location + i] !== data[i]) {
  36102. changed = true;
  36103. this._bufferData[location + i] = data[i];
  36104. }
  36105. }
  36106. this._needSync = this._needSync || changed;
  36107. }
  36108. else {
  36109. // No cache for dynamic
  36110. for (var i = 0; i < size; i++) {
  36111. this._bufferData[location + i] = data[i];
  36112. }
  36113. }
  36114. };
  36115. // Update methods
  36116. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36117. // To match std140, matrix must be realigned
  36118. for (var i = 0; i < 3; i++) {
  36119. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36120. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36121. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36122. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36123. }
  36124. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36125. };
  36126. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36127. this._currentEffect.setMatrix3x3(name, matrix);
  36128. };
  36129. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36130. this._currentEffect.setMatrix2x2(name, matrix);
  36131. };
  36132. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36133. // To match std140, matrix must be realigned
  36134. for (var i = 0; i < 2; i++) {
  36135. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36136. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36137. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36138. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36139. }
  36140. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36141. };
  36142. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36143. this._currentEffect.setFloat(name, x);
  36144. };
  36145. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36146. UniformBuffer._tempBuffer[0] = x;
  36147. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36148. };
  36149. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36150. if (suffix === void 0) { suffix = ""; }
  36151. this._currentEffect.setFloat2(name + suffix, x, y);
  36152. };
  36153. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36154. if (suffix === void 0) { suffix = ""; }
  36155. UniformBuffer._tempBuffer[0] = x;
  36156. UniformBuffer._tempBuffer[1] = y;
  36157. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36158. };
  36159. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36160. if (suffix === void 0) { suffix = ""; }
  36161. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36162. };
  36163. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36164. if (suffix === void 0) { suffix = ""; }
  36165. UniformBuffer._tempBuffer[0] = x;
  36166. UniformBuffer._tempBuffer[1] = y;
  36167. UniformBuffer._tempBuffer[2] = z;
  36168. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36169. };
  36170. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36171. if (suffix === void 0) { suffix = ""; }
  36172. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36173. };
  36174. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36175. if (suffix === void 0) { suffix = ""; }
  36176. UniformBuffer._tempBuffer[0] = x;
  36177. UniformBuffer._tempBuffer[1] = y;
  36178. UniformBuffer._tempBuffer[2] = z;
  36179. UniformBuffer._tempBuffer[3] = w;
  36180. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36181. };
  36182. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36183. this._currentEffect.setMatrix(name, mat);
  36184. };
  36185. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36186. this.updateUniform(name, mat.toArray(), 16);
  36187. };
  36188. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36189. this._currentEffect.setVector3(name, vector);
  36190. };
  36191. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36192. vector.toArray(UniformBuffer._tempBuffer);
  36193. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36194. };
  36195. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36196. this._currentEffect.setVector4(name, vector);
  36197. };
  36198. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36199. vector.toArray(UniformBuffer._tempBuffer);
  36200. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36201. };
  36202. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36203. if (suffix === void 0) { suffix = ""; }
  36204. this._currentEffect.setColor3(name + suffix, color);
  36205. };
  36206. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36207. if (suffix === void 0) { suffix = ""; }
  36208. color.toArray(UniformBuffer._tempBuffer);
  36209. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36210. };
  36211. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36212. if (suffix === void 0) { suffix = ""; }
  36213. this._currentEffect.setColor4(name + suffix, color, alpha);
  36214. };
  36215. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36216. if (suffix === void 0) { suffix = ""; }
  36217. color.toArray(UniformBuffer._tempBuffer);
  36218. UniformBuffer._tempBuffer[3] = alpha;
  36219. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36220. };
  36221. /**
  36222. * Sets a sampler uniform on the effect.
  36223. * @param {string} name Name of the sampler.
  36224. * @param {Texture} texture
  36225. */
  36226. UniformBuffer.prototype.setTexture = function (name, texture) {
  36227. this._currentEffect.setTexture(name, texture);
  36228. };
  36229. /**
  36230. * Directly updates the value of the uniform in the cache AND on the GPU.
  36231. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36232. * @param {number[]|Float32Array} data Flattened data
  36233. */
  36234. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36235. this.updateUniform(uniformName, data, data.length);
  36236. this.update();
  36237. };
  36238. /**
  36239. * Binds this uniform buffer to an effect.
  36240. * @param {Effect} effect
  36241. * @param {string} name Name of the uniform block in the shader.
  36242. */
  36243. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36244. this._currentEffect = effect;
  36245. if (this._noUBO || !this._buffer) {
  36246. return;
  36247. }
  36248. effect.bindUniformBuffer(this._buffer, name);
  36249. };
  36250. /**
  36251. * Disposes the uniform buffer.
  36252. */
  36253. UniformBuffer.prototype.dispose = function () {
  36254. if (this._noUBO) {
  36255. return;
  36256. }
  36257. var index = this._engine._uniformBuffers.indexOf(this);
  36258. if (index !== -1) {
  36259. this._engine._uniformBuffers.splice(index, 1);
  36260. }
  36261. if (!this._buffer) {
  36262. return;
  36263. }
  36264. if (this._engine._releaseBuffer(this._buffer)) {
  36265. this._buffer = null;
  36266. }
  36267. };
  36268. // Pool for avoiding memory leaks
  36269. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36270. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36271. return UniformBuffer;
  36272. }());
  36273. BABYLON.UniformBuffer = UniformBuffer;
  36274. })(BABYLON || (BABYLON = {}));
  36275. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36276. var BABYLON;
  36277. (function (BABYLON) {
  36278. /**
  36279. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36280. */
  36281. var VertexData = /** @class */ (function () {
  36282. function VertexData() {
  36283. }
  36284. /**
  36285. * Uses the passed data array to set the set the values for the specified kind of data
  36286. * @param data a linear array of floating numbers
  36287. * @param kind the type of data that is being set, eg positions, colors etc
  36288. */
  36289. VertexData.prototype.set = function (data, kind) {
  36290. switch (kind) {
  36291. case BABYLON.VertexBuffer.PositionKind:
  36292. this.positions = data;
  36293. break;
  36294. case BABYLON.VertexBuffer.NormalKind:
  36295. this.normals = data;
  36296. break;
  36297. case BABYLON.VertexBuffer.TangentKind:
  36298. this.tangents = data;
  36299. break;
  36300. case BABYLON.VertexBuffer.UVKind:
  36301. this.uvs = data;
  36302. break;
  36303. case BABYLON.VertexBuffer.UV2Kind:
  36304. this.uvs2 = data;
  36305. break;
  36306. case BABYLON.VertexBuffer.UV3Kind:
  36307. this.uvs3 = data;
  36308. break;
  36309. case BABYLON.VertexBuffer.UV4Kind:
  36310. this.uvs4 = data;
  36311. break;
  36312. case BABYLON.VertexBuffer.UV5Kind:
  36313. this.uvs5 = data;
  36314. break;
  36315. case BABYLON.VertexBuffer.UV6Kind:
  36316. this.uvs6 = data;
  36317. break;
  36318. case BABYLON.VertexBuffer.ColorKind:
  36319. this.colors = data;
  36320. break;
  36321. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36322. this.matricesIndices = data;
  36323. break;
  36324. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36325. this.matricesWeights = data;
  36326. break;
  36327. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36328. this.matricesIndicesExtra = data;
  36329. break;
  36330. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36331. this.matricesWeightsExtra = data;
  36332. break;
  36333. }
  36334. };
  36335. /**
  36336. * Associates the vertexData to the passed Mesh.
  36337. * Sets it as updatable or not (default `false`)
  36338. * @param mesh the mesh the vertexData is applied to
  36339. * @param updatable when used and having the value true allows new data to update the vertexData
  36340. * @returns the VertexData
  36341. */
  36342. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36343. this._applyTo(mesh, updatable);
  36344. return this;
  36345. };
  36346. /**
  36347. * Associates the vertexData to the passed Geometry.
  36348. * Sets it as updatable or not (default `false`)
  36349. * @param geometry the geometry the vertexData is applied to
  36350. * @param updatable when used and having the value true allows new data to update the vertexData
  36351. * @returns VertexData
  36352. */
  36353. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36354. this._applyTo(geometry, updatable);
  36355. return this;
  36356. };
  36357. /**
  36358. * Updates the associated mesh
  36359. * @param mesh the mesh to be updated
  36360. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36361. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36362. * @returns VertexData
  36363. */
  36364. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36365. this._update(mesh);
  36366. return this;
  36367. };
  36368. /**
  36369. * Updates the associated geometry
  36370. * @param geometry the geometry to be updated
  36371. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36372. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36373. * @returns VertexData.
  36374. */
  36375. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36376. this._update(geometry);
  36377. return this;
  36378. };
  36379. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36380. if (updatable === void 0) { updatable = false; }
  36381. if (this.positions) {
  36382. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36383. }
  36384. if (this.normals) {
  36385. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36386. }
  36387. if (this.tangents) {
  36388. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36389. }
  36390. if (this.uvs) {
  36391. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36392. }
  36393. if (this.uvs2) {
  36394. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36395. }
  36396. if (this.uvs3) {
  36397. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36398. }
  36399. if (this.uvs4) {
  36400. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36401. }
  36402. if (this.uvs5) {
  36403. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36404. }
  36405. if (this.uvs6) {
  36406. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36407. }
  36408. if (this.colors) {
  36409. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36410. }
  36411. if (this.matricesIndices) {
  36412. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36413. }
  36414. if (this.matricesWeights) {
  36415. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36416. }
  36417. if (this.matricesIndicesExtra) {
  36418. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36419. }
  36420. if (this.matricesWeightsExtra) {
  36421. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36422. }
  36423. if (this.indices) {
  36424. meshOrGeometry.setIndices(this.indices, null, updatable);
  36425. }
  36426. return this;
  36427. };
  36428. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36429. if (this.positions) {
  36430. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36431. }
  36432. if (this.normals) {
  36433. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36434. }
  36435. if (this.tangents) {
  36436. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36437. }
  36438. if (this.uvs) {
  36439. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36440. }
  36441. if (this.uvs2) {
  36442. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36443. }
  36444. if (this.uvs3) {
  36445. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36446. }
  36447. if (this.uvs4) {
  36448. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36449. }
  36450. if (this.uvs5) {
  36451. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36452. }
  36453. if (this.uvs6) {
  36454. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36455. }
  36456. if (this.colors) {
  36457. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36458. }
  36459. if (this.matricesIndices) {
  36460. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36461. }
  36462. if (this.matricesWeights) {
  36463. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36464. }
  36465. if (this.matricesIndicesExtra) {
  36466. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36467. }
  36468. if (this.matricesWeightsExtra) {
  36469. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36470. }
  36471. if (this.indices) {
  36472. meshOrGeometry.setIndices(this.indices, null);
  36473. }
  36474. return this;
  36475. };
  36476. /**
  36477. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36478. * @param matrix the transforming matrix
  36479. * @returns the VertexData
  36480. */
  36481. VertexData.prototype.transform = function (matrix) {
  36482. var transformed = BABYLON.Vector3.Zero();
  36483. var index;
  36484. if (this.positions) {
  36485. var position = BABYLON.Vector3.Zero();
  36486. for (index = 0; index < this.positions.length; index += 3) {
  36487. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36488. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36489. this.positions[index] = transformed.x;
  36490. this.positions[index + 1] = transformed.y;
  36491. this.positions[index + 2] = transformed.z;
  36492. }
  36493. }
  36494. if (this.normals) {
  36495. var normal = BABYLON.Vector3.Zero();
  36496. for (index = 0; index < this.normals.length; index += 3) {
  36497. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36498. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36499. this.normals[index] = transformed.x;
  36500. this.normals[index + 1] = transformed.y;
  36501. this.normals[index + 2] = transformed.z;
  36502. }
  36503. }
  36504. if (this.tangents) {
  36505. var tangent = BABYLON.Vector4.Zero();
  36506. var tangentTransformed = BABYLON.Vector4.Zero();
  36507. for (index = 0; index < this.tangents.length; index += 4) {
  36508. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36509. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36510. this.tangents[index] = tangentTransformed.x;
  36511. this.tangents[index + 1] = tangentTransformed.y;
  36512. this.tangents[index + 2] = tangentTransformed.z;
  36513. this.tangents[index + 3] = tangentTransformed.w;
  36514. }
  36515. }
  36516. return this;
  36517. };
  36518. /**
  36519. * Merges the passed VertexData into the current one
  36520. * @param other the VertexData to be merged into the current one
  36521. * @returns the modified VertexData
  36522. */
  36523. VertexData.prototype.merge = function (other) {
  36524. this._validate();
  36525. other._validate();
  36526. if (!this.normals !== !other.normals ||
  36527. !this.tangents !== !other.tangents ||
  36528. !this.uvs !== !other.uvs ||
  36529. !this.uvs2 !== !other.uvs2 ||
  36530. !this.uvs3 !== !other.uvs3 ||
  36531. !this.uvs4 !== !other.uvs4 ||
  36532. !this.uvs5 !== !other.uvs5 ||
  36533. !this.uvs6 !== !other.uvs6 ||
  36534. !this.colors !== !other.colors ||
  36535. !this.matricesIndices !== !other.matricesIndices ||
  36536. !this.matricesWeights !== !other.matricesWeights ||
  36537. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36538. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36539. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36540. }
  36541. if (other.indices) {
  36542. if (!this.indices) {
  36543. this.indices = [];
  36544. }
  36545. var offset = this.positions ? this.positions.length / 3 : 0;
  36546. for (var index = 0; index < other.indices.length; index++) {
  36547. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36548. this.indices.push(other.indices[index] + offset);
  36549. }
  36550. }
  36551. this.positions = this._mergeElement(this.positions, other.positions);
  36552. this.normals = this._mergeElement(this.normals, other.normals);
  36553. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36554. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36555. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36556. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36557. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36558. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36559. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36560. this.colors = this._mergeElement(this.colors, other.colors);
  36561. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36562. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36563. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36564. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36565. return this;
  36566. };
  36567. VertexData.prototype._mergeElement = function (source, other) {
  36568. if (!source) {
  36569. return other;
  36570. }
  36571. if (!other) {
  36572. return source;
  36573. }
  36574. var len = other.length + source.length;
  36575. var isSrcTypedArray = source instanceof Float32Array;
  36576. var isOthTypedArray = other instanceof Float32Array;
  36577. // use non-loop method when the source is Float32Array
  36578. if (isSrcTypedArray) {
  36579. var ret32 = new Float32Array(len);
  36580. ret32.set(source);
  36581. ret32.set(other, source.length);
  36582. return ret32;
  36583. // source is number[], when other is also use concat
  36584. }
  36585. else if (!isOthTypedArray) {
  36586. return source.concat(other);
  36587. // source is a number[], but other is a Float32Array, loop required
  36588. }
  36589. else {
  36590. var ret = source.slice(0); // copy source to a separate array
  36591. for (var i = 0, len = other.length; i < len; i++) {
  36592. ret.push(other[i]);
  36593. }
  36594. return ret;
  36595. }
  36596. };
  36597. VertexData.prototype._validate = function () {
  36598. if (!this.positions) {
  36599. throw new Error("Positions are required");
  36600. }
  36601. var getElementCount = function (kind, values) {
  36602. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36603. if ((values.length % stride) !== 0) {
  36604. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36605. }
  36606. return values.length / stride;
  36607. };
  36608. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36609. var validateElementCount = function (kind, values) {
  36610. var elementCount = getElementCount(kind, values);
  36611. if (elementCount !== positionsElementCount) {
  36612. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36613. }
  36614. };
  36615. if (this.normals)
  36616. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36617. if (this.tangents)
  36618. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36619. if (this.uvs)
  36620. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36621. if (this.uvs2)
  36622. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36623. if (this.uvs3)
  36624. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36625. if (this.uvs4)
  36626. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36627. if (this.uvs5)
  36628. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36629. if (this.uvs6)
  36630. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36631. if (this.colors)
  36632. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36633. if (this.matricesIndices)
  36634. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36635. if (this.matricesWeights)
  36636. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36637. if (this.matricesIndicesExtra)
  36638. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36639. if (this.matricesWeightsExtra)
  36640. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36641. };
  36642. /**
  36643. * Serializes the VertexData
  36644. * @returns a serialized object
  36645. */
  36646. VertexData.prototype.serialize = function () {
  36647. var serializationObject = this.serialize();
  36648. if (this.positions) {
  36649. serializationObject.positions = this.positions;
  36650. }
  36651. if (this.normals) {
  36652. serializationObject.normals = this.normals;
  36653. }
  36654. if (this.tangents) {
  36655. serializationObject.tangents = this.tangents;
  36656. }
  36657. if (this.uvs) {
  36658. serializationObject.uvs = this.uvs;
  36659. }
  36660. if (this.uvs2) {
  36661. serializationObject.uvs2 = this.uvs2;
  36662. }
  36663. if (this.uvs3) {
  36664. serializationObject.uvs3 = this.uvs3;
  36665. }
  36666. if (this.uvs4) {
  36667. serializationObject.uvs4 = this.uvs4;
  36668. }
  36669. if (this.uvs5) {
  36670. serializationObject.uvs5 = this.uvs5;
  36671. }
  36672. if (this.uvs6) {
  36673. serializationObject.uvs6 = this.uvs6;
  36674. }
  36675. if (this.colors) {
  36676. serializationObject.colors = this.colors;
  36677. }
  36678. if (this.matricesIndices) {
  36679. serializationObject.matricesIndices = this.matricesIndices;
  36680. serializationObject.matricesIndices._isExpanded = true;
  36681. }
  36682. if (this.matricesWeights) {
  36683. serializationObject.matricesWeights = this.matricesWeights;
  36684. }
  36685. if (this.matricesIndicesExtra) {
  36686. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36687. serializationObject.matricesIndicesExtra._isExpanded = true;
  36688. }
  36689. if (this.matricesWeightsExtra) {
  36690. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36691. }
  36692. serializationObject.indices = this.indices;
  36693. return serializationObject;
  36694. };
  36695. // Statics
  36696. /**
  36697. * Extracts the vertexData from a mesh
  36698. * @param mesh the mesh from which to extract the VertexData
  36699. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36700. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36701. * @returns the object VertexData associated to the passed mesh
  36702. */
  36703. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36704. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36705. };
  36706. /**
  36707. * Extracts the vertexData from the geometry
  36708. * @param geometry the geometry from which to extract the VertexData
  36709. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36710. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36711. * @returns the object VertexData associated to the passed mesh
  36712. */
  36713. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36714. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36715. };
  36716. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36717. var result = new VertexData();
  36718. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36719. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36720. }
  36721. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36722. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36723. }
  36724. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36725. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36726. }
  36727. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36728. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36729. }
  36730. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36731. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36732. }
  36733. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36734. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36735. }
  36736. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36737. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36738. }
  36739. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36740. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36741. }
  36742. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36743. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36744. }
  36745. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36746. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36747. }
  36748. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36749. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36750. }
  36751. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36752. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36753. }
  36754. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36755. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36756. }
  36757. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36758. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36759. }
  36760. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36761. return result;
  36762. };
  36763. /**
  36764. * Creates the VertexData for a Ribbon
  36765. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36766. * * pathArray array of paths, each of which an array of successive Vector3
  36767. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36768. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36769. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36770. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36771. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36772. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36773. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36774. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36775. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36776. * @returns the VertexData of the ribbon
  36777. */
  36778. VertexData.CreateRibbon = function (options) {
  36779. var pathArray = options.pathArray;
  36780. var closeArray = options.closeArray || false;
  36781. var closePath = options.closePath || false;
  36782. var invertUV = options.invertUV || false;
  36783. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36784. var offset = options.offset || defaultOffset;
  36785. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36786. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36787. var customUV = options.uvs;
  36788. var customColors = options.colors;
  36789. var positions = [];
  36790. var indices = [];
  36791. var normals = [];
  36792. var uvs = [];
  36793. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36794. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36795. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36796. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36797. var minlg; // minimal length among all paths from pathArray
  36798. var lg = []; // array of path lengths : nb of vertex per path
  36799. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36800. var p; // path iterator
  36801. var i; // point iterator
  36802. var j; // point iterator
  36803. // if single path in pathArray
  36804. if (pathArray.length < 2) {
  36805. var ar1 = [];
  36806. var ar2 = [];
  36807. for (i = 0; i < pathArray[0].length - offset; i++) {
  36808. ar1.push(pathArray[0][i]);
  36809. ar2.push(pathArray[0][i + offset]);
  36810. }
  36811. pathArray = [ar1, ar2];
  36812. }
  36813. // positions and horizontal distances (u)
  36814. var idc = 0;
  36815. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36816. var path;
  36817. var l;
  36818. minlg = pathArray[0].length;
  36819. var vectlg;
  36820. var dist;
  36821. for (p = 0; p < pathArray.length; p++) {
  36822. uTotalDistance[p] = 0;
  36823. us[p] = [0];
  36824. path = pathArray[p];
  36825. l = path.length;
  36826. minlg = (minlg < l) ? minlg : l;
  36827. j = 0;
  36828. while (j < l) {
  36829. positions.push(path[j].x, path[j].y, path[j].z);
  36830. if (j > 0) {
  36831. vectlg = path[j].subtract(path[j - 1]).length();
  36832. dist = vectlg + uTotalDistance[p];
  36833. us[p].push(dist);
  36834. uTotalDistance[p] = dist;
  36835. }
  36836. j++;
  36837. }
  36838. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36839. j--;
  36840. positions.push(path[0].x, path[0].y, path[0].z);
  36841. vectlg = path[j].subtract(path[0]).length();
  36842. dist = vectlg + uTotalDistance[p];
  36843. us[p].push(dist);
  36844. uTotalDistance[p] = dist;
  36845. }
  36846. lg[p] = l + closePathCorr;
  36847. idx[p] = idc;
  36848. idc += (l + closePathCorr);
  36849. }
  36850. // vertical distances (v)
  36851. var path1;
  36852. var path2;
  36853. var vertex1 = null;
  36854. var vertex2 = null;
  36855. for (i = 0; i < minlg + closePathCorr; i++) {
  36856. vTotalDistance[i] = 0;
  36857. vs[i] = [0];
  36858. for (p = 0; p < pathArray.length - 1; p++) {
  36859. path1 = pathArray[p];
  36860. path2 = pathArray[p + 1];
  36861. if (i === minlg) { // closePath
  36862. vertex1 = path1[0];
  36863. vertex2 = path2[0];
  36864. }
  36865. else {
  36866. vertex1 = path1[i];
  36867. vertex2 = path2[i];
  36868. }
  36869. vectlg = vertex2.subtract(vertex1).length();
  36870. dist = vectlg + vTotalDistance[i];
  36871. vs[i].push(dist);
  36872. vTotalDistance[i] = dist;
  36873. }
  36874. if (closeArray && vertex2 && vertex1) {
  36875. path1 = pathArray[p];
  36876. path2 = pathArray[0];
  36877. if (i === minlg) { // closePath
  36878. vertex2 = path2[0];
  36879. }
  36880. vectlg = vertex2.subtract(vertex1).length();
  36881. dist = vectlg + vTotalDistance[i];
  36882. vTotalDistance[i] = dist;
  36883. }
  36884. }
  36885. // uvs
  36886. var u;
  36887. var v;
  36888. if (customUV) {
  36889. for (p = 0; p < customUV.length; p++) {
  36890. uvs.push(customUV[p].x, customUV[p].y);
  36891. }
  36892. }
  36893. else {
  36894. for (p = 0; p < pathArray.length; p++) {
  36895. for (i = 0; i < minlg + closePathCorr; i++) {
  36896. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36897. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36898. if (invertUV) {
  36899. uvs.push(v, u);
  36900. }
  36901. else {
  36902. uvs.push(u, v);
  36903. }
  36904. }
  36905. }
  36906. }
  36907. // indices
  36908. p = 0; // path index
  36909. var pi = 0; // positions array index
  36910. var l1 = lg[p] - 1; // path1 length
  36911. var l2 = lg[p + 1] - 1; // path2 length
  36912. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36913. var shft = idx[1] - idx[0]; // shift
  36914. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36915. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36916. // 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
  36917. indices.push(pi, pi + shft, pi + 1);
  36918. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36919. pi += 1;
  36920. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36921. p++;
  36922. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36923. shft = idx[0] - idx[p];
  36924. l1 = lg[p] - 1;
  36925. l2 = lg[0] - 1;
  36926. }
  36927. else {
  36928. shft = idx[p + 1] - idx[p];
  36929. l1 = lg[p] - 1;
  36930. l2 = lg[p + 1] - 1;
  36931. }
  36932. pi = idx[p];
  36933. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36934. }
  36935. }
  36936. // normals
  36937. VertexData.ComputeNormals(positions, indices, normals);
  36938. if (closePath) { // update both the first and last vertex normals to their average value
  36939. var indexFirst = 0;
  36940. var indexLast = 0;
  36941. for (p = 0; p < pathArray.length; p++) {
  36942. indexFirst = idx[p] * 3;
  36943. if (p + 1 < pathArray.length) {
  36944. indexLast = (idx[p + 1] - 1) * 3;
  36945. }
  36946. else {
  36947. indexLast = normals.length - 3;
  36948. }
  36949. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36950. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36951. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36952. normals[indexLast] = normals[indexFirst];
  36953. normals[indexLast + 1] = normals[indexFirst + 1];
  36954. normals[indexLast + 2] = normals[indexFirst + 2];
  36955. }
  36956. }
  36957. // sides
  36958. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36959. // Colors
  36960. var colors = null;
  36961. if (customColors) {
  36962. colors = new Float32Array(customColors.length * 4);
  36963. for (var c = 0; c < customColors.length; c++) {
  36964. colors[c * 4] = customColors[c].r;
  36965. colors[c * 4 + 1] = customColors[c].g;
  36966. colors[c * 4 + 2] = customColors[c].b;
  36967. colors[c * 4 + 3] = customColors[c].a;
  36968. }
  36969. }
  36970. // Result
  36971. var vertexData = new VertexData();
  36972. var positions32 = new Float32Array(positions);
  36973. var normals32 = new Float32Array(normals);
  36974. var uvs32 = new Float32Array(uvs);
  36975. vertexData.indices = indices;
  36976. vertexData.positions = positions32;
  36977. vertexData.normals = normals32;
  36978. vertexData.uvs = uvs32;
  36979. if (colors) {
  36980. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36981. }
  36982. if (closePath) {
  36983. vertexData._idx = idx;
  36984. }
  36985. return vertexData;
  36986. };
  36987. /**
  36988. * Creates the VertexData for a box
  36989. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36990. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36991. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36992. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36993. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36994. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36995. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36996. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36997. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36998. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36999. * @returns the VertexData of the box
  37000. */
  37001. VertexData.CreateBox = function (options) {
  37002. var normalsSource = [
  37003. new BABYLON.Vector3(0, 0, 1),
  37004. new BABYLON.Vector3(0, 0, -1),
  37005. new BABYLON.Vector3(1, 0, 0),
  37006. new BABYLON.Vector3(-1, 0, 0),
  37007. new BABYLON.Vector3(0, 1, 0),
  37008. new BABYLON.Vector3(0, -1, 0)
  37009. ];
  37010. var indices = [];
  37011. var positions = [];
  37012. var normals = [];
  37013. var uvs = [];
  37014. var width = options.width || options.size || 1;
  37015. var height = options.height || options.size || 1;
  37016. var depth = options.depth || options.size || 1;
  37017. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37018. var faceUV = options.faceUV || new Array(6);
  37019. var faceColors = options.faceColors;
  37020. var colors = [];
  37021. // default face colors and UV if undefined
  37022. for (var f = 0; f < 6; f++) {
  37023. if (faceUV[f] === undefined) {
  37024. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37025. }
  37026. if (faceColors && faceColors[f] === undefined) {
  37027. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37028. }
  37029. }
  37030. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37031. // Create each face in turn.
  37032. for (var index = 0; index < normalsSource.length; index++) {
  37033. var normal = normalsSource[index];
  37034. // Get two vectors perpendicular to the face normal and to each other.
  37035. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37036. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37037. // Six indices (two triangles) per face.
  37038. var verticesLength = positions.length / 3;
  37039. indices.push(verticesLength);
  37040. indices.push(verticesLength + 1);
  37041. indices.push(verticesLength + 2);
  37042. indices.push(verticesLength);
  37043. indices.push(verticesLength + 2);
  37044. indices.push(verticesLength + 3);
  37045. // Four vertices per face.
  37046. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37047. positions.push(vertex.x, vertex.y, vertex.z);
  37048. normals.push(normal.x, normal.y, normal.z);
  37049. uvs.push(faceUV[index].z, faceUV[index].w);
  37050. if (faceColors) {
  37051. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37052. }
  37053. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37054. positions.push(vertex.x, vertex.y, vertex.z);
  37055. normals.push(normal.x, normal.y, normal.z);
  37056. uvs.push(faceUV[index].x, faceUV[index].w);
  37057. if (faceColors) {
  37058. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37059. }
  37060. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37061. positions.push(vertex.x, vertex.y, vertex.z);
  37062. normals.push(normal.x, normal.y, normal.z);
  37063. uvs.push(faceUV[index].x, faceUV[index].y);
  37064. if (faceColors) {
  37065. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37066. }
  37067. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37068. positions.push(vertex.x, vertex.y, vertex.z);
  37069. normals.push(normal.x, normal.y, normal.z);
  37070. uvs.push(faceUV[index].z, faceUV[index].y);
  37071. if (faceColors) {
  37072. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37073. }
  37074. }
  37075. // sides
  37076. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37077. // Result
  37078. var vertexData = new VertexData();
  37079. vertexData.indices = indices;
  37080. vertexData.positions = positions;
  37081. vertexData.normals = normals;
  37082. vertexData.uvs = uvs;
  37083. if (faceColors) {
  37084. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37085. vertexData.colors = totalColors;
  37086. }
  37087. return vertexData;
  37088. };
  37089. /**
  37090. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37091. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37092. * * segments sets the number of horizontal strips optional, default 32
  37093. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37094. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37095. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37096. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37097. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  37098. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  37099. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37100. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37101. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37102. * @returns the VertexData of the ellipsoid
  37103. */
  37104. VertexData.CreateSphere = function (options) {
  37105. var segments = options.segments || 32;
  37106. var diameterX = options.diameterX || options.diameter || 1;
  37107. var diameterY = options.diameterY || options.diameter || 1;
  37108. var diameterZ = options.diameterZ || options.diameter || 1;
  37109. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37110. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37111. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37112. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37113. var totalZRotationSteps = 2 + segments;
  37114. var totalYRotationSteps = 2 * totalZRotationSteps;
  37115. var indices = [];
  37116. var positions = [];
  37117. var normals = [];
  37118. var uvs = [];
  37119. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37120. var normalizedZ = zRotationStep / totalZRotationSteps;
  37121. var angleZ = normalizedZ * Math.PI * slice;
  37122. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37123. var normalizedY = yRotationStep / totalYRotationSteps;
  37124. var angleY = normalizedY * Math.PI * 2 * arc;
  37125. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37126. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37127. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37128. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37129. var vertex = complete.multiply(radius);
  37130. var normal = complete.divide(radius).normalize();
  37131. positions.push(vertex.x, vertex.y, vertex.z);
  37132. normals.push(normal.x, normal.y, normal.z);
  37133. uvs.push(normalizedY, normalizedZ);
  37134. }
  37135. if (zRotationStep > 0) {
  37136. var verticesCount = positions.length / 3;
  37137. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37138. indices.push((firstIndex));
  37139. indices.push((firstIndex + 1));
  37140. indices.push(firstIndex + totalYRotationSteps + 1);
  37141. indices.push((firstIndex + totalYRotationSteps + 1));
  37142. indices.push((firstIndex + 1));
  37143. indices.push((firstIndex + totalYRotationSteps + 2));
  37144. }
  37145. }
  37146. }
  37147. // Sides
  37148. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37149. // Result
  37150. var vertexData = new VertexData();
  37151. vertexData.indices = indices;
  37152. vertexData.positions = positions;
  37153. vertexData.normals = normals;
  37154. vertexData.uvs = uvs;
  37155. return vertexData;
  37156. };
  37157. /**
  37158. * Creates the VertexData for a cylinder, cone or prism
  37159. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37160. * * height sets the height (y direction) of the cylinder, optional, default 2
  37161. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37162. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37163. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37164. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37165. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37166. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  37167. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37168. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37169. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37170. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37171. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37172. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37173. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37174. * @returns the VertexData of the cylinder, cone or prism
  37175. */
  37176. VertexData.CreateCylinder = function (options) {
  37177. var height = options.height || 2;
  37178. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37179. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37180. var tessellation = options.tessellation || 24;
  37181. var subdivisions = options.subdivisions || 1;
  37182. var hasRings = options.hasRings ? true : false;
  37183. var enclose = options.enclose ? true : false;
  37184. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37185. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37186. var faceUV = options.faceUV || new Array(3);
  37187. var faceColors = options.faceColors;
  37188. // default face colors and UV if undefined
  37189. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37190. var ringNb = (hasRings) ? subdivisions : 1;
  37191. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37192. var f;
  37193. for (f = 0; f < surfaceNb; f++) {
  37194. if (faceColors && faceColors[f] === undefined) {
  37195. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37196. }
  37197. }
  37198. for (f = 0; f < surfaceNb; f++) {
  37199. if (faceUV && faceUV[f] === undefined) {
  37200. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37201. }
  37202. }
  37203. var indices = new Array();
  37204. var positions = new Array();
  37205. var normals = new Array();
  37206. var uvs = new Array();
  37207. var colors = new Array();
  37208. var angle_step = Math.PI * 2 * arc / tessellation;
  37209. var angle;
  37210. var h;
  37211. var radius;
  37212. var tan = (diameterBottom - diameterTop) / 2 / height;
  37213. var ringVertex = BABYLON.Vector3.Zero();
  37214. var ringNormal = BABYLON.Vector3.Zero();
  37215. var ringFirstVertex = BABYLON.Vector3.Zero();
  37216. var ringFirstNormal = BABYLON.Vector3.Zero();
  37217. var quadNormal = BABYLON.Vector3.Zero();
  37218. var Y = BABYLON.Axis.Y;
  37219. // positions, normals, uvs
  37220. var i;
  37221. var j;
  37222. var r;
  37223. var ringIdx = 1;
  37224. var s = 1; // surface index
  37225. var cs = 0;
  37226. var v = 0;
  37227. for (i = 0; i <= subdivisions; i++) {
  37228. h = i / subdivisions;
  37229. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37230. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37231. for (r = 0; r < ringIdx; r++) {
  37232. if (hasRings) {
  37233. s += r;
  37234. }
  37235. if (enclose) {
  37236. s += 2 * r;
  37237. }
  37238. for (j = 0; j <= tessellation; j++) {
  37239. angle = j * angle_step;
  37240. // position
  37241. ringVertex.x = Math.cos(-angle) * radius;
  37242. ringVertex.y = -height / 2 + h * height;
  37243. ringVertex.z = Math.sin(-angle) * radius;
  37244. // normal
  37245. if (diameterTop === 0 && i === subdivisions) {
  37246. // if no top cap, reuse former normals
  37247. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37248. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37249. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37250. }
  37251. else {
  37252. ringNormal.x = ringVertex.x;
  37253. ringNormal.z = ringVertex.z;
  37254. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37255. ringNormal.normalize();
  37256. }
  37257. // keep first ring vertex values for enclose
  37258. if (j === 0) {
  37259. ringFirstVertex.copyFrom(ringVertex);
  37260. ringFirstNormal.copyFrom(ringNormal);
  37261. }
  37262. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37263. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37264. if (hasRings) {
  37265. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37266. }
  37267. else {
  37268. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37269. }
  37270. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37271. if (faceColors) {
  37272. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37273. }
  37274. }
  37275. // if enclose, add four vertices and their dedicated normals
  37276. if (arc !== 1 && enclose) {
  37277. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37278. positions.push(0, ringVertex.y, 0);
  37279. positions.push(0, ringVertex.y, 0);
  37280. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37281. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37282. quadNormal.normalize();
  37283. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37284. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37285. quadNormal.normalize();
  37286. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37287. if (hasRings) {
  37288. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37289. }
  37290. else {
  37291. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37292. }
  37293. uvs.push(faceUV[s + 1].x, v);
  37294. uvs.push(faceUV[s + 1].z, v);
  37295. if (hasRings) {
  37296. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37297. }
  37298. else {
  37299. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37300. }
  37301. uvs.push(faceUV[s + 2].x, v);
  37302. uvs.push(faceUV[s + 2].z, v);
  37303. if (faceColors) {
  37304. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37305. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37306. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37307. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37308. }
  37309. }
  37310. if (cs !== s) {
  37311. cs = s;
  37312. }
  37313. }
  37314. }
  37315. // indices
  37316. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37317. var s;
  37318. i = 0;
  37319. for (s = 0; s < subdivisions; s++) {
  37320. var i0 = 0;
  37321. var i1 = 0;
  37322. var i2 = 0;
  37323. var i3 = 0;
  37324. for (j = 0; j < tessellation; j++) {
  37325. i0 = i * (e + 1) + j;
  37326. i1 = (i + 1) * (e + 1) + j;
  37327. i2 = i * (e + 1) + (j + 1);
  37328. i3 = (i + 1) * (e + 1) + (j + 1);
  37329. indices.push(i0, i1, i2);
  37330. indices.push(i3, i2, i1);
  37331. }
  37332. if (arc !== 1 && enclose) { // if enclose, add two quads
  37333. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37334. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37335. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37336. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37337. }
  37338. i = (hasRings) ? (i + 2) : (i + 1);
  37339. }
  37340. // Caps
  37341. var createCylinderCap = function (isTop) {
  37342. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37343. if (radius === 0) {
  37344. return;
  37345. }
  37346. // Cap positions, normals & uvs
  37347. var angle;
  37348. var circleVector;
  37349. var i;
  37350. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37351. var c = null;
  37352. if (faceColors) {
  37353. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37354. }
  37355. // cap center
  37356. var vbase = positions.length / 3;
  37357. var offset = isTop ? height / 2 : -height / 2;
  37358. var center = new BABYLON.Vector3(0, offset, 0);
  37359. positions.push(center.x, center.y, center.z);
  37360. normals.push(0, isTop ? 1 : -1, 0);
  37361. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37362. if (c) {
  37363. colors.push(c.r, c.g, c.b, c.a);
  37364. }
  37365. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37366. for (i = 0; i <= tessellation; i++) {
  37367. angle = Math.PI * 2 * i * arc / tessellation;
  37368. var cos = Math.cos(-angle);
  37369. var sin = Math.sin(-angle);
  37370. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37371. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37372. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37373. normals.push(0, isTop ? 1 : -1, 0);
  37374. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37375. if (c) {
  37376. colors.push(c.r, c.g, c.b, c.a);
  37377. }
  37378. }
  37379. // Cap indices
  37380. for (i = 0; i < tessellation; i++) {
  37381. if (!isTop) {
  37382. indices.push(vbase);
  37383. indices.push(vbase + (i + 1));
  37384. indices.push(vbase + (i + 2));
  37385. }
  37386. else {
  37387. indices.push(vbase);
  37388. indices.push(vbase + (i + 2));
  37389. indices.push(vbase + (i + 1));
  37390. }
  37391. }
  37392. };
  37393. // add caps to geometry
  37394. createCylinderCap(false);
  37395. createCylinderCap(true);
  37396. // Sides
  37397. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37398. var vertexData = new VertexData();
  37399. vertexData.indices = indices;
  37400. vertexData.positions = positions;
  37401. vertexData.normals = normals;
  37402. vertexData.uvs = uvs;
  37403. if (faceColors) {
  37404. vertexData.colors = colors;
  37405. }
  37406. return vertexData;
  37407. };
  37408. /**
  37409. * Creates the VertexData for a torus
  37410. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37411. * * diameter the diameter of the torus, optional default 1
  37412. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37413. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37414. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37415. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37416. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37417. * @returns the VertexData of the torus
  37418. */
  37419. VertexData.CreateTorus = function (options) {
  37420. var indices = [];
  37421. var positions = [];
  37422. var normals = [];
  37423. var uvs = [];
  37424. var diameter = options.diameter || 1;
  37425. var thickness = options.thickness || 0.5;
  37426. var tessellation = options.tessellation || 16;
  37427. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37428. var stride = tessellation + 1;
  37429. for (var i = 0; i <= tessellation; i++) {
  37430. var u = i / tessellation;
  37431. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37432. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37433. for (var j = 0; j <= tessellation; j++) {
  37434. var v = 1 - j / tessellation;
  37435. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37436. var dx = Math.cos(innerAngle);
  37437. var dy = Math.sin(innerAngle);
  37438. // Create a vertex.
  37439. var normal = new BABYLON.Vector3(dx, dy, 0);
  37440. var position = normal.scale(thickness / 2);
  37441. var textureCoordinate = new BABYLON.Vector2(u, v);
  37442. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37443. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37444. positions.push(position.x, position.y, position.z);
  37445. normals.push(normal.x, normal.y, normal.z);
  37446. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37447. // And create indices for two triangles.
  37448. var nextI = (i + 1) % stride;
  37449. var nextJ = (j + 1) % stride;
  37450. indices.push(i * stride + j);
  37451. indices.push(i * stride + nextJ);
  37452. indices.push(nextI * stride + j);
  37453. indices.push(i * stride + nextJ);
  37454. indices.push(nextI * stride + nextJ);
  37455. indices.push(nextI * stride + j);
  37456. }
  37457. }
  37458. // Sides
  37459. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37460. // Result
  37461. var vertexData = new VertexData();
  37462. vertexData.indices = indices;
  37463. vertexData.positions = positions;
  37464. vertexData.normals = normals;
  37465. vertexData.uvs = uvs;
  37466. return vertexData;
  37467. };
  37468. /**
  37469. * Creates the VertexData of the LineSystem
  37470. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37471. * - lines an array of lines, each line being an array of successive Vector3
  37472. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37473. * @returns the VertexData of the LineSystem
  37474. */
  37475. VertexData.CreateLineSystem = function (options) {
  37476. var indices = [];
  37477. var positions = [];
  37478. var lines = options.lines;
  37479. var colors = options.colors;
  37480. var vertexColors = [];
  37481. var idx = 0;
  37482. for (var l = 0; l < lines.length; l++) {
  37483. var points = lines[l];
  37484. for (var index = 0; index < points.length; index++) {
  37485. positions.push(points[index].x, points[index].y, points[index].z);
  37486. if (colors) {
  37487. var color = colors[l];
  37488. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37489. }
  37490. if (index > 0) {
  37491. indices.push(idx - 1);
  37492. indices.push(idx);
  37493. }
  37494. idx++;
  37495. }
  37496. }
  37497. var vertexData = new VertexData();
  37498. vertexData.indices = indices;
  37499. vertexData.positions = positions;
  37500. if (colors) {
  37501. vertexData.colors = vertexColors;
  37502. }
  37503. return vertexData;
  37504. };
  37505. /**
  37506. * Create the VertexData for a DashedLines
  37507. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37508. * - points an array successive Vector3
  37509. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37510. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37511. * - dashNb the intended total number of dashes, optional, default 200
  37512. * @returns the VertexData for the DashedLines
  37513. */
  37514. VertexData.CreateDashedLines = function (options) {
  37515. var dashSize = options.dashSize || 3;
  37516. var gapSize = options.gapSize || 1;
  37517. var dashNb = options.dashNb || 200;
  37518. var points = options.points;
  37519. var positions = new Array();
  37520. var indices = new Array();
  37521. var curvect = BABYLON.Vector3.Zero();
  37522. var lg = 0;
  37523. var nb = 0;
  37524. var shft = 0;
  37525. var dashshft = 0;
  37526. var curshft = 0;
  37527. var idx = 0;
  37528. var i = 0;
  37529. for (i = 0; i < points.length - 1; i++) {
  37530. points[i + 1].subtractToRef(points[i], curvect);
  37531. lg += curvect.length();
  37532. }
  37533. shft = lg / dashNb;
  37534. dashshft = dashSize * shft / (dashSize + gapSize);
  37535. for (i = 0; i < points.length - 1; i++) {
  37536. points[i + 1].subtractToRef(points[i], curvect);
  37537. nb = Math.floor(curvect.length() / shft);
  37538. curvect.normalize();
  37539. for (var j = 0; j < nb; j++) {
  37540. curshft = shft * j;
  37541. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37542. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37543. indices.push(idx, idx + 1);
  37544. idx += 2;
  37545. }
  37546. }
  37547. // Result
  37548. var vertexData = new VertexData();
  37549. vertexData.positions = positions;
  37550. vertexData.indices = indices;
  37551. return vertexData;
  37552. };
  37553. /**
  37554. * Creates the VertexData for a Ground
  37555. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37556. * - width the width (x direction) of the ground, optional, default 1
  37557. * - height the height (z direction) of the ground, optional, default 1
  37558. * - subdivisions the number of subdivisions per side, optional, default 1
  37559. * @returns the VertexData of the Ground
  37560. */
  37561. VertexData.CreateGround = function (options) {
  37562. var indices = [];
  37563. var positions = [];
  37564. var normals = [];
  37565. var uvs = [];
  37566. var row, col;
  37567. var width = options.width || 1;
  37568. var height = options.height || 1;
  37569. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37570. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37571. for (row = 0; row <= subdivisionsY; row++) {
  37572. for (col = 0; col <= subdivisionsX; col++) {
  37573. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37574. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37575. positions.push(position.x, position.y, position.z);
  37576. normals.push(normal.x, normal.y, normal.z);
  37577. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37578. }
  37579. }
  37580. for (row = 0; row < subdivisionsY; row++) {
  37581. for (col = 0; col < subdivisionsX; col++) {
  37582. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37583. indices.push(col + 1 + row * (subdivisionsX + 1));
  37584. indices.push(col + row * (subdivisionsX + 1));
  37585. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37586. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37587. indices.push(col + row * (subdivisionsX + 1));
  37588. }
  37589. }
  37590. // Result
  37591. var vertexData = new VertexData();
  37592. vertexData.indices = indices;
  37593. vertexData.positions = positions;
  37594. vertexData.normals = normals;
  37595. vertexData.uvs = uvs;
  37596. return vertexData;
  37597. };
  37598. /**
  37599. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37600. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37601. * * xmin the ground minimum X coordinate, optional, default -1
  37602. * * zmin the ground minimum Z coordinate, optional, default -1
  37603. * * xmax the ground maximum X coordinate, optional, default 1
  37604. * * zmax the ground maximum Z coordinate, optional, default 1
  37605. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37606. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37607. * @returns the VertexData of the TiledGround
  37608. */
  37609. VertexData.CreateTiledGround = function (options) {
  37610. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37611. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37612. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37613. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37614. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37615. var precision = options.precision || { w: 1, h: 1 };
  37616. var indices = new Array();
  37617. var positions = new Array();
  37618. var normals = new Array();
  37619. var uvs = new Array();
  37620. var row, col, tileRow, tileCol;
  37621. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37622. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37623. precision.w = (precision.w < 1) ? 1 : precision.w;
  37624. precision.h = (precision.h < 1) ? 1 : precision.h;
  37625. var tileSize = {
  37626. 'w': (xmax - xmin) / subdivisions.w,
  37627. 'h': (zmax - zmin) / subdivisions.h
  37628. };
  37629. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37630. // Indices
  37631. var base = positions.length / 3;
  37632. var rowLength = precision.w + 1;
  37633. for (row = 0; row < precision.h; row++) {
  37634. for (col = 0; col < precision.w; col++) {
  37635. var square = [
  37636. base + col + row * rowLength,
  37637. base + (col + 1) + row * rowLength,
  37638. base + (col + 1) + (row + 1) * rowLength,
  37639. base + col + (row + 1) * rowLength
  37640. ];
  37641. indices.push(square[1]);
  37642. indices.push(square[2]);
  37643. indices.push(square[3]);
  37644. indices.push(square[0]);
  37645. indices.push(square[1]);
  37646. indices.push(square[3]);
  37647. }
  37648. }
  37649. // Position, normals and uvs
  37650. var position = BABYLON.Vector3.Zero();
  37651. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37652. for (row = 0; row <= precision.h; row++) {
  37653. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37654. for (col = 0; col <= precision.w; col++) {
  37655. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37656. position.y = 0;
  37657. positions.push(position.x, position.y, position.z);
  37658. normals.push(normal.x, normal.y, normal.z);
  37659. uvs.push(col / precision.w, row / precision.h);
  37660. }
  37661. }
  37662. }
  37663. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37664. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37665. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37666. }
  37667. }
  37668. // Result
  37669. var vertexData = new VertexData();
  37670. vertexData.indices = indices;
  37671. vertexData.positions = positions;
  37672. vertexData.normals = normals;
  37673. vertexData.uvs = uvs;
  37674. return vertexData;
  37675. };
  37676. /**
  37677. * Creates the VertexData of the Ground designed from a heightmap
  37678. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37679. * * width the width (x direction) of the ground
  37680. * * height the height (z direction) of the ground
  37681. * * subdivisions the number of subdivisions per side
  37682. * * minHeight the minimum altitude on the ground, optional, default 0
  37683. * * maxHeight the maximum altitude on the ground, optional default 1
  37684. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37685. * * buffer the array holding the image color data
  37686. * * bufferWidth the width of image
  37687. * * bufferHeight the height of image
  37688. * @returns the VertexData of the Ground designed from a heightmap
  37689. */
  37690. VertexData.CreateGroundFromHeightMap = function (options) {
  37691. var indices = [];
  37692. var positions = [];
  37693. var normals = [];
  37694. var uvs = [];
  37695. var row, col;
  37696. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37697. // Vertices
  37698. for (row = 0; row <= options.subdivisions; row++) {
  37699. for (col = 0; col <= options.subdivisions; col++) {
  37700. 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));
  37701. // Compute height
  37702. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37703. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37704. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37705. var r = options.buffer[pos] / 255.0;
  37706. var g = options.buffer[pos + 1] / 255.0;
  37707. var b = options.buffer[pos + 2] / 255.0;
  37708. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37709. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37710. // Add vertex
  37711. positions.push(position.x, position.y, position.z);
  37712. normals.push(0, 0, 0);
  37713. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37714. }
  37715. }
  37716. // Indices
  37717. for (row = 0; row < options.subdivisions; row++) {
  37718. for (col = 0; col < options.subdivisions; col++) {
  37719. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37720. indices.push(col + 1 + row * (options.subdivisions + 1));
  37721. indices.push(col + row * (options.subdivisions + 1));
  37722. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37723. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37724. indices.push(col + row * (options.subdivisions + 1));
  37725. }
  37726. }
  37727. // Normals
  37728. VertexData.ComputeNormals(positions, indices, normals);
  37729. // Result
  37730. var vertexData = new VertexData();
  37731. vertexData.indices = indices;
  37732. vertexData.positions = positions;
  37733. vertexData.normals = normals;
  37734. vertexData.uvs = uvs;
  37735. return vertexData;
  37736. };
  37737. /**
  37738. * Creates the VertexData for a Plane
  37739. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37740. * * size sets the width and height of the plane to the value of size, optional default 1
  37741. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37742. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37743. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37744. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37745. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37746. * @returns the VertexData of the box
  37747. */
  37748. VertexData.CreatePlane = function (options) {
  37749. var indices = [];
  37750. var positions = [];
  37751. var normals = [];
  37752. var uvs = [];
  37753. var width = options.width || options.size || 1;
  37754. var height = options.height || options.size || 1;
  37755. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37756. // Vertices
  37757. var halfWidth = width / 2.0;
  37758. var halfHeight = height / 2.0;
  37759. positions.push(-halfWidth, -halfHeight, 0);
  37760. normals.push(0, 0, -1.0);
  37761. uvs.push(0.0, 0.0);
  37762. positions.push(halfWidth, -halfHeight, 0);
  37763. normals.push(0, 0, -1.0);
  37764. uvs.push(1.0, 0.0);
  37765. positions.push(halfWidth, halfHeight, 0);
  37766. normals.push(0, 0, -1.0);
  37767. uvs.push(1.0, 1.0);
  37768. positions.push(-halfWidth, halfHeight, 0);
  37769. normals.push(0, 0, -1.0);
  37770. uvs.push(0.0, 1.0);
  37771. // Indices
  37772. indices.push(0);
  37773. indices.push(1);
  37774. indices.push(2);
  37775. indices.push(0);
  37776. indices.push(2);
  37777. indices.push(3);
  37778. // Sides
  37779. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37780. // Result
  37781. var vertexData = new VertexData();
  37782. vertexData.indices = indices;
  37783. vertexData.positions = positions;
  37784. vertexData.normals = normals;
  37785. vertexData.uvs = uvs;
  37786. return vertexData;
  37787. };
  37788. /**
  37789. * Creates the VertexData of the Disc or regular Polygon
  37790. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37791. * * radius the radius of the disc, optional default 0.5
  37792. * * tessellation the number of polygon sides, optional, default 64
  37793. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37794. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37795. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37796. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37797. * @returns the VertexData of the box
  37798. */
  37799. VertexData.CreateDisc = function (options) {
  37800. var positions = new Array();
  37801. var indices = new Array();
  37802. var normals = new Array();
  37803. var uvs = new Array();
  37804. var radius = options.radius || 0.5;
  37805. var tessellation = options.tessellation || 64;
  37806. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37807. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37808. // positions and uvs
  37809. positions.push(0, 0, 0); // disc center first
  37810. uvs.push(0.5, 0.5);
  37811. var theta = Math.PI * 2 * arc;
  37812. var step = theta / tessellation;
  37813. for (var a = 0; a < theta; a += step) {
  37814. var x = Math.cos(a);
  37815. var y = Math.sin(a);
  37816. var u = (x + 1) / 2;
  37817. var v = (1 - y) / 2;
  37818. positions.push(radius * x, radius * y, 0);
  37819. uvs.push(u, v);
  37820. }
  37821. if (arc === 1) {
  37822. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37823. uvs.push(uvs[2], uvs[3]);
  37824. }
  37825. //indices
  37826. var vertexNb = positions.length / 3;
  37827. for (var i = 1; i < vertexNb - 1; i++) {
  37828. indices.push(i + 1, 0, i);
  37829. }
  37830. // result
  37831. VertexData.ComputeNormals(positions, indices, normals);
  37832. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37833. var vertexData = new VertexData();
  37834. vertexData.indices = indices;
  37835. vertexData.positions = positions;
  37836. vertexData.normals = normals;
  37837. vertexData.uvs = uvs;
  37838. return vertexData;
  37839. };
  37840. /**
  37841. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37842. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37843. * @param polygon a mesh built from polygonTriangulation.build()
  37844. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37845. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37846. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37847. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37848. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37849. * @returns the VertexData of the Polygon
  37850. */
  37851. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37852. var faceUV = fUV || new Array(3);
  37853. var faceColors = fColors;
  37854. var colors = [];
  37855. // default face colors and UV if undefined
  37856. for (var f = 0; f < 3; f++) {
  37857. if (faceUV[f] === undefined) {
  37858. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37859. }
  37860. if (faceColors && faceColors[f] === undefined) {
  37861. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37862. }
  37863. }
  37864. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37865. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37866. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37867. var indices = polygon.getIndices();
  37868. // set face colours and textures
  37869. var idx = 0;
  37870. var face = 0;
  37871. for (var index = 0; index < normals.length; index += 3) {
  37872. //Edge Face no. 1
  37873. if (Math.abs(normals[index + 1]) < 0.001) {
  37874. face = 1;
  37875. }
  37876. //Top Face no. 0
  37877. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37878. face = 0;
  37879. }
  37880. //Bottom Face no. 2
  37881. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37882. face = 2;
  37883. }
  37884. idx = index / 3;
  37885. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37886. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37887. if (faceColors) {
  37888. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37889. }
  37890. }
  37891. // sides
  37892. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37893. // Result
  37894. var vertexData = new VertexData();
  37895. vertexData.indices = indices;
  37896. vertexData.positions = positions;
  37897. vertexData.normals = normals;
  37898. vertexData.uvs = uvs;
  37899. if (faceColors) {
  37900. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37901. vertexData.colors = totalColors;
  37902. }
  37903. return vertexData;
  37904. };
  37905. /**
  37906. * Creates the VertexData of the IcoSphere
  37907. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37908. * * radius the radius of the IcoSphere, optional default 1
  37909. * * radiusX allows stretching in the x direction, optional, default radius
  37910. * * radiusY allows stretching in the y direction, optional, default radius
  37911. * * radiusZ allows stretching in the z direction, optional, default radius
  37912. * * flat when true creates a flat shaded mesh, optional, default true
  37913. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37914. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37915. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37916. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37917. * @returns the VertexData of the IcoSphere
  37918. */
  37919. VertexData.CreateIcoSphere = function (options) {
  37920. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37921. var radius = options.radius || 1;
  37922. var flat = (options.flat === undefined) ? true : options.flat;
  37923. var subdivisions = options.subdivisions || 4;
  37924. var radiusX = options.radiusX || radius;
  37925. var radiusY = options.radiusY || radius;
  37926. var radiusZ = options.radiusZ || radius;
  37927. var t = (1 + Math.sqrt(5)) / 2;
  37928. // 12 vertex x,y,z
  37929. var ico_vertices = [
  37930. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37931. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37932. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37933. ];
  37934. // index of 3 vertex makes a face of icopshere
  37935. var ico_indices = [
  37936. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37937. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37938. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37939. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37940. ];
  37941. // vertex for uv have aliased position, not for UV
  37942. var vertices_unalias_id = [
  37943. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37944. // vertex alias
  37945. 0,
  37946. 2,
  37947. 3,
  37948. 3,
  37949. 3,
  37950. 4,
  37951. 7,
  37952. 8,
  37953. 9,
  37954. 9,
  37955. 10,
  37956. 11 // 23: B + 12
  37957. ];
  37958. // uv as integer step (not pixels !)
  37959. var ico_vertexuv = [
  37960. 5, 1, 3, 1, 6, 4, 0, 0,
  37961. 5, 3, 4, 2, 2, 2, 4, 0,
  37962. 2, 0, 1, 1, 6, 0, 6, 2,
  37963. // vertex alias (for same vertex on different faces)
  37964. 0, 4,
  37965. 3, 3,
  37966. 4, 4,
  37967. 3, 1,
  37968. 4, 2,
  37969. 4, 4,
  37970. 0, 2,
  37971. 1, 1,
  37972. 2, 2,
  37973. 3, 3,
  37974. 1, 3,
  37975. 2, 4 // 23: B + 12
  37976. ];
  37977. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37978. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37979. // First island of uv mapping
  37980. // v = 4h 3+ 2
  37981. // v = 3h 9+ 4
  37982. // v = 2h 9+ 5 B
  37983. // v = 1h 9 1 0
  37984. // v = 0h 3 8 7 A
  37985. // u = 0 1 2 3 4 5 6 *a
  37986. // Second island of uv mapping
  37987. // v = 4h 0+ B+ 4+
  37988. // v = 3h A+ 2+
  37989. // v = 2h 7+ 6 3+
  37990. // v = 1h 8+ 3+
  37991. // v = 0h
  37992. // u = 0 1 2 3 4 5 6 *a
  37993. // Face layout on texture UV mapping
  37994. // ============
  37995. // \ 4 /\ 16 / ======
  37996. // \ / \ / /\ 11 /
  37997. // \/ 7 \/ / \ /
  37998. // ======= / 10 \/
  37999. // /\ 17 /\ =======
  38000. // / \ / \ \ 15 /\
  38001. // / 8 \/ 12 \ \ / \
  38002. // ============ \/ 6 \
  38003. // \ 18 /\ ============
  38004. // \ / \ \ 5 /\ 0 /
  38005. // \/ 13 \ \ / \ /
  38006. // ======= \/ 1 \/
  38007. // =============
  38008. // /\ 19 /\ 2 /\
  38009. // / \ / \ / \
  38010. // / 14 \/ 9 \/ 3 \
  38011. // ===================
  38012. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38013. var ustep = 138 / 1024;
  38014. var vstep = 239 / 1024;
  38015. var uoffset = 60 / 1024;
  38016. var voffset = 26 / 1024;
  38017. // Second island should have margin, not to touch the first island
  38018. // avoid any borderline artefact in pixel rounding
  38019. var island_u_offset = -40 / 1024;
  38020. var island_v_offset = +20 / 1024;
  38021. // face is either island 0 or 1 :
  38022. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38023. var island = [
  38024. 0, 0, 0, 0, 1,
  38025. 0, 0, 1, 1, 0,
  38026. 0, 0, 1, 1, 0,
  38027. 0, 1, 1, 1, 0 // 15 - 19
  38028. ];
  38029. var indices = new Array();
  38030. var positions = new Array();
  38031. var normals = new Array();
  38032. var uvs = new Array();
  38033. var current_indice = 0;
  38034. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38035. var face_vertex_pos = new Array(3);
  38036. var face_vertex_uv = new Array(3);
  38037. var v012;
  38038. for (v012 = 0; v012 < 3; v012++) {
  38039. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38040. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38041. }
  38042. // create all with normals
  38043. for (var face = 0; face < 20; face++) {
  38044. // 3 vertex per face
  38045. for (v012 = 0; v012 < 3; v012++) {
  38046. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38047. var v_id = ico_indices[3 * face + v012];
  38048. // vertex have 3D position (x,y,z)
  38049. 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]);
  38050. // Normalize to get normal, then scale to radius
  38051. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38052. // uv Coordinates from vertex ID
  38053. 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);
  38054. }
  38055. // Subdivide the face (interpolate pos, norm, uv)
  38056. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38057. // - norm is linear interpolation of vertex corner normal
  38058. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38059. // - uv is linear interpolation
  38060. //
  38061. // Topology is as below for sub-divide by 2
  38062. // vertex shown as v0,v1,v2
  38063. // interp index is i1 to progress in range [v0,v1[
  38064. // interp index is i2 to progress in range [v0,v2[
  38065. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38066. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38067. //
  38068. //
  38069. // i2 v2
  38070. // ^ ^
  38071. // / / \
  38072. // / / \
  38073. // / / \
  38074. // / / (0,1) \
  38075. // / #---------\
  38076. // / / \ (0,0)'/ \
  38077. // / / \ / \
  38078. // / / \ / \
  38079. // / / (0,0) \ / (1,0) \
  38080. // / #---------#---------\
  38081. // v0 v1
  38082. //
  38083. // --------------------> i1
  38084. //
  38085. // interp of (i1,i2):
  38086. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38087. // along i1 : lerp(x0,x1, i1/(S-i2))
  38088. //
  38089. // centroid of triangle is needed to get help normal computation
  38090. // (c1,c2) are used for centroid location
  38091. var interp_vertex = function (i1, i2, c1, c2) {
  38092. // vertex is interpolated from
  38093. // - face_vertex_pos[0..2]
  38094. // - face_vertex_uv[0..2]
  38095. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38096. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38097. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38098. pos_interp.normalize();
  38099. var vertex_normal;
  38100. if (flat) {
  38101. // in flat mode, recalculate normal as face centroid normal
  38102. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38103. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38104. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38105. }
  38106. else {
  38107. // in smooth mode, recalculate normal from each single vertex position
  38108. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38109. }
  38110. // Vertex normal need correction due to X,Y,Z radius scaling
  38111. vertex_normal.x /= radiusX;
  38112. vertex_normal.y /= radiusY;
  38113. vertex_normal.z /= radiusZ;
  38114. vertex_normal.normalize();
  38115. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38116. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38117. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38118. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38119. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38120. uvs.push(uv_interp.x, uv_interp.y);
  38121. // push each vertex has member of a face
  38122. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38123. indices.push(current_indice);
  38124. current_indice++;
  38125. };
  38126. for (var i2 = 0; i2 < subdivisions; i2++) {
  38127. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38128. // face : (i1,i2) for /\ :
  38129. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38130. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38131. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38132. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38133. if (i1 + i2 + 1 < subdivisions) {
  38134. // face : (i1,i2)' for \/ :
  38135. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38136. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38137. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38138. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38139. }
  38140. }
  38141. }
  38142. }
  38143. // Sides
  38144. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38145. // Result
  38146. var vertexData = new VertexData();
  38147. vertexData.indices = indices;
  38148. vertexData.positions = positions;
  38149. vertexData.normals = normals;
  38150. vertexData.uvs = uvs;
  38151. return vertexData;
  38152. };
  38153. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38154. /**
  38155. * Creates the VertexData for a Polyhedron
  38156. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38157. * * type provided types are:
  38158. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38159. * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  38160. * * size the size of the IcoSphere, optional default 1
  38161. * * sizeX allows stretching in the x direction, optional, default size
  38162. * * sizeY allows stretching in the y direction, optional, default size
  38163. * * sizeZ allows stretching in the z direction, optional, default size
  38164. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  38165. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38166. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38167. * * flat when true creates a flat shaded mesh, optional, default true
  38168. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38169. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38170. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38171. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38172. * @returns the VertexData of the Polyhedron
  38173. */
  38174. VertexData.CreatePolyhedron = function (options) {
  38175. // provided polyhedron types :
  38176. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38177. // 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)
  38178. var polyhedra = [];
  38179. 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]] };
  38180. 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]] };
  38181. polyhedra[2] = {
  38182. 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]],
  38183. 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]]
  38184. };
  38185. polyhedra[3] = {
  38186. 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]],
  38187. 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]]
  38188. };
  38189. polyhedra[4] = {
  38190. 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]],
  38191. 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]]
  38192. };
  38193. 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]] };
  38194. 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]] };
  38195. 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]] };
  38196. 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]] };
  38197. 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]] };
  38198. 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]] };
  38199. 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]] };
  38200. 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]] };
  38201. 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]] };
  38202. polyhedra[14] = {
  38203. 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]],
  38204. 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]]
  38205. };
  38206. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38207. var size = options.size;
  38208. var sizeX = options.sizeX || size || 1;
  38209. var sizeY = options.sizeY || size || 1;
  38210. var sizeZ = options.sizeZ || size || 1;
  38211. var data = options.custom || polyhedra[type];
  38212. var nbfaces = data.face.length;
  38213. var faceUV = options.faceUV || new Array(nbfaces);
  38214. var faceColors = options.faceColors;
  38215. var flat = (options.flat === undefined) ? true : options.flat;
  38216. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38217. var positions = new Array();
  38218. var indices = new Array();
  38219. var normals = new Array();
  38220. var uvs = new Array();
  38221. var colors = new Array();
  38222. var index = 0;
  38223. var faceIdx = 0; // face cursor in the array "indexes"
  38224. var indexes = new Array();
  38225. var i = 0;
  38226. var f = 0;
  38227. var u, v, ang, x, y, tmp;
  38228. // default face colors and UV if undefined
  38229. if (flat) {
  38230. for (f = 0; f < nbfaces; f++) {
  38231. if (faceColors && faceColors[f] === undefined) {
  38232. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38233. }
  38234. if (faceUV && faceUV[f] === undefined) {
  38235. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38236. }
  38237. }
  38238. }
  38239. if (!flat) {
  38240. for (i = 0; i < data.vertex.length; i++) {
  38241. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38242. uvs.push(0, 0);
  38243. }
  38244. for (f = 0; f < nbfaces; f++) {
  38245. for (i = 0; i < data.face[f].length - 2; i++) {
  38246. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38247. }
  38248. }
  38249. }
  38250. else {
  38251. for (f = 0; f < nbfaces; f++) {
  38252. var fl = data.face[f].length; // number of vertices of the current face
  38253. ang = 2 * Math.PI / fl;
  38254. x = 0.5 * Math.tan(ang / 2);
  38255. y = 0.5;
  38256. // positions, uvs, colors
  38257. for (i = 0; i < fl; i++) {
  38258. // positions
  38259. 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);
  38260. indexes.push(index);
  38261. index++;
  38262. // uvs
  38263. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38264. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38265. uvs.push(u, v);
  38266. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38267. y = x * Math.sin(ang) + y * Math.cos(ang);
  38268. x = tmp;
  38269. // colors
  38270. if (faceColors) {
  38271. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38272. }
  38273. }
  38274. // indices from indexes
  38275. for (i = 0; i < fl - 2; i++) {
  38276. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38277. }
  38278. faceIdx += fl;
  38279. }
  38280. }
  38281. VertexData.ComputeNormals(positions, indices, normals);
  38282. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38283. var vertexData = new VertexData();
  38284. vertexData.positions = positions;
  38285. vertexData.indices = indices;
  38286. vertexData.normals = normals;
  38287. vertexData.uvs = uvs;
  38288. if (faceColors && flat) {
  38289. vertexData.colors = colors;
  38290. }
  38291. return vertexData;
  38292. };
  38293. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38294. /**
  38295. * Creates the VertexData for a TorusKnot
  38296. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38297. * * radius the radius of the torus knot, optional, default 2
  38298. * * tube the thickness of the tube, optional, default 0.5
  38299. * * radialSegments the number of sides on each tube segments, optional, default 32
  38300. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38301. * * p the number of windings around the z axis, optional, default 2
  38302. * * q the number of windings around the x axis, optional, default 3
  38303. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38304. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38305. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38306. * @returns the VertexData of the Torus Knot
  38307. */
  38308. VertexData.CreateTorusKnot = function (options) {
  38309. var indices = new Array();
  38310. var positions = new Array();
  38311. var normals = new Array();
  38312. var uvs = new Array();
  38313. var radius = options.radius || 2;
  38314. var tube = options.tube || 0.5;
  38315. var radialSegments = options.radialSegments || 32;
  38316. var tubularSegments = options.tubularSegments || 32;
  38317. var p = options.p || 2;
  38318. var q = options.q || 3;
  38319. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38320. // Helper
  38321. var getPos = function (angle) {
  38322. var cu = Math.cos(angle);
  38323. var su = Math.sin(angle);
  38324. var quOverP = q / p * angle;
  38325. var cs = Math.cos(quOverP);
  38326. var tx = radius * (2 + cs) * 0.5 * cu;
  38327. var ty = radius * (2 + cs) * su * 0.5;
  38328. var tz = radius * Math.sin(quOverP) * 0.5;
  38329. return new BABYLON.Vector3(tx, ty, tz);
  38330. };
  38331. // Vertices
  38332. var i;
  38333. var j;
  38334. for (i = 0; i <= radialSegments; i++) {
  38335. var modI = i % radialSegments;
  38336. var u = modI / radialSegments * 2 * p * Math.PI;
  38337. var p1 = getPos(u);
  38338. var p2 = getPos(u + 0.01);
  38339. var tang = p2.subtract(p1);
  38340. var n = p2.add(p1);
  38341. var bitan = BABYLON.Vector3.Cross(tang, n);
  38342. n = BABYLON.Vector3.Cross(bitan, tang);
  38343. bitan.normalize();
  38344. n.normalize();
  38345. for (j = 0; j < tubularSegments; j++) {
  38346. var modJ = j % tubularSegments;
  38347. var v = modJ / tubularSegments * 2 * Math.PI;
  38348. var cx = -tube * Math.cos(v);
  38349. var cy = tube * Math.sin(v);
  38350. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38351. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38352. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38353. uvs.push(i / radialSegments);
  38354. uvs.push(j / tubularSegments);
  38355. }
  38356. }
  38357. for (i = 0; i < radialSegments; i++) {
  38358. for (j = 0; j < tubularSegments; j++) {
  38359. var jNext = (j + 1) % tubularSegments;
  38360. var a = i * tubularSegments + j;
  38361. var b = (i + 1) * tubularSegments + j;
  38362. var c = (i + 1) * tubularSegments + jNext;
  38363. var d = i * tubularSegments + jNext;
  38364. indices.push(d);
  38365. indices.push(b);
  38366. indices.push(a);
  38367. indices.push(d);
  38368. indices.push(c);
  38369. indices.push(b);
  38370. }
  38371. }
  38372. // Normals
  38373. VertexData.ComputeNormals(positions, indices, normals);
  38374. // Sides
  38375. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38376. // Result
  38377. var vertexData = new VertexData();
  38378. vertexData.indices = indices;
  38379. vertexData.positions = positions;
  38380. vertexData.normals = normals;
  38381. vertexData.uvs = uvs;
  38382. return vertexData;
  38383. };
  38384. // Tools
  38385. /**
  38386. * Compute normals for given positions and indices
  38387. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38388. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38389. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38390. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38391. * * facetNormals : optional array of facet normals (vector3)
  38392. * * facetPositions : optional array of facet positions (vector3)
  38393. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38394. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38395. * * bInfo : optional bounding info, required for facetPartitioning computation
  38396. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38397. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38398. * * useRightHandedSystem: optional boolean to for right handed system computation
  38399. * * depthSort : optional boolean to enable the facet depth sort computation
  38400. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38401. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38402. */
  38403. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38404. // temporary scalar variables
  38405. var index = 0; // facet index
  38406. var p1p2x = 0.0; // p1p2 vector x coordinate
  38407. var p1p2y = 0.0; // p1p2 vector y coordinate
  38408. var p1p2z = 0.0; // p1p2 vector z coordinate
  38409. var p3p2x = 0.0; // p3p2 vector x coordinate
  38410. var p3p2y = 0.0; // p3p2 vector y coordinate
  38411. var p3p2z = 0.0; // p3p2 vector z coordinate
  38412. var faceNormalx = 0.0; // facet normal x coordinate
  38413. var faceNormaly = 0.0; // facet normal y coordinate
  38414. var faceNormalz = 0.0; // facet normal z coordinate
  38415. var length = 0.0; // facet normal length before normalization
  38416. var v1x = 0; // vector1 x index in the positions array
  38417. var v1y = 0; // vector1 y index in the positions array
  38418. var v1z = 0; // vector1 z index in the positions array
  38419. var v2x = 0; // vector2 x index in the positions array
  38420. var v2y = 0; // vector2 y index in the positions array
  38421. var v2z = 0; // vector2 z index in the positions array
  38422. var v3x = 0; // vector3 x index in the positions array
  38423. var v3y = 0; // vector3 y index in the positions array
  38424. var v3z = 0; // vector3 z index in the positions array
  38425. var computeFacetNormals = false;
  38426. var computeFacetPositions = false;
  38427. var computeFacetPartitioning = false;
  38428. var computeDepthSort = false;
  38429. var faceNormalSign = 1;
  38430. var ratio = 0;
  38431. var distanceTo = null;
  38432. if (options) {
  38433. computeFacetNormals = (options.facetNormals) ? true : false;
  38434. computeFacetPositions = (options.facetPositions) ? true : false;
  38435. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38436. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38437. ratio = options.ratio || 0;
  38438. computeDepthSort = (options.depthSort) ? true : false;
  38439. distanceTo = (options.distanceTo);
  38440. if (computeDepthSort) {
  38441. if (distanceTo === undefined) {
  38442. distanceTo = BABYLON.Vector3.Zero();
  38443. }
  38444. var depthSortedFacets = options.depthSortedFacets;
  38445. }
  38446. }
  38447. // facetPartitioning reinit if needed
  38448. var xSubRatio = 0;
  38449. var ySubRatio = 0;
  38450. var zSubRatio = 0;
  38451. var subSq = 0;
  38452. if (computeFacetPartitioning && options && options.bbSize) {
  38453. var ox = 0; // X partitioning index for facet position
  38454. var oy = 0; // Y partinioning index for facet position
  38455. var oz = 0; // Z partinioning index for facet position
  38456. var b1x = 0; // X partitioning index for facet v1 vertex
  38457. var b1y = 0; // Y partitioning index for facet v1 vertex
  38458. var b1z = 0; // z partitioning index for facet v1 vertex
  38459. var b2x = 0; // X partitioning index for facet v2 vertex
  38460. var b2y = 0; // Y partitioning index for facet v2 vertex
  38461. var b2z = 0; // Z partitioning index for facet v2 vertex
  38462. var b3x = 0; // X partitioning index for facet v3 vertex
  38463. var b3y = 0; // Y partitioning index for facet v3 vertex
  38464. var b3z = 0; // Z partitioning index for facet v3 vertex
  38465. var block_idx_o = 0; // facet barycenter block index
  38466. var block_idx_v1 = 0; // v1 vertex block index
  38467. var block_idx_v2 = 0; // v2 vertex block index
  38468. var block_idx_v3 = 0; // v3 vertex block index
  38469. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38470. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38471. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38472. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38473. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38474. subSq = options.subDiv.max * options.subDiv.max;
  38475. options.facetPartitioning.length = 0;
  38476. }
  38477. // reset the normals
  38478. for (index = 0; index < positions.length; index++) {
  38479. normals[index] = 0.0;
  38480. }
  38481. // Loop : 1 indice triplet = 1 facet
  38482. var nbFaces = (indices.length / 3) | 0;
  38483. for (index = 0; index < nbFaces; index++) {
  38484. // get the indexes of the coordinates of each vertex of the facet
  38485. v1x = indices[index * 3] * 3;
  38486. v1y = v1x + 1;
  38487. v1z = v1x + 2;
  38488. v2x = indices[index * 3 + 1] * 3;
  38489. v2y = v2x + 1;
  38490. v2z = v2x + 2;
  38491. v3x = indices[index * 3 + 2] * 3;
  38492. v3y = v3x + 1;
  38493. v3z = v3x + 2;
  38494. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38495. p1p2y = positions[v1y] - positions[v2y];
  38496. p1p2z = positions[v1z] - positions[v2z];
  38497. p3p2x = positions[v3x] - positions[v2x];
  38498. p3p2y = positions[v3y] - positions[v2y];
  38499. p3p2z = positions[v3z] - positions[v2z];
  38500. // compute the face normal with the cross product
  38501. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38502. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38503. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38504. // normalize this normal and store it in the array facetData
  38505. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38506. length = (length === 0) ? 1.0 : length;
  38507. faceNormalx /= length;
  38508. faceNormaly /= length;
  38509. faceNormalz /= length;
  38510. if (computeFacetNormals && options) {
  38511. options.facetNormals[index].x = faceNormalx;
  38512. options.facetNormals[index].y = faceNormaly;
  38513. options.facetNormals[index].z = faceNormalz;
  38514. }
  38515. if (computeFacetPositions && options) {
  38516. // compute and the facet barycenter coordinates in the array facetPositions
  38517. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38518. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38519. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38520. }
  38521. if (computeFacetPartitioning && options) {
  38522. // store the facet indexes in arrays in the main facetPartitioning array :
  38523. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38524. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38525. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38526. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38527. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38528. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38529. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38530. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38531. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38532. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38533. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38534. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38535. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38536. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38537. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38538. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38539. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38540. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38541. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38542. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38543. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38544. // push each facet index in each block containing the vertex
  38545. options.facetPartitioning[block_idx_v1].push(index);
  38546. if (block_idx_v2 != block_idx_v1) {
  38547. options.facetPartitioning[block_idx_v2].push(index);
  38548. }
  38549. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38550. options.facetPartitioning[block_idx_v3].push(index);
  38551. }
  38552. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38553. options.facetPartitioning[block_idx_o].push(index);
  38554. }
  38555. }
  38556. if (computeDepthSort && options && options.facetPositions) {
  38557. var dsf = depthSortedFacets[index];
  38558. dsf.ind = index * 3;
  38559. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38560. }
  38561. // compute the normals anyway
  38562. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38563. normals[v1y] += faceNormaly;
  38564. normals[v1z] += faceNormalz;
  38565. normals[v2x] += faceNormalx;
  38566. normals[v2y] += faceNormaly;
  38567. normals[v2z] += faceNormalz;
  38568. normals[v3x] += faceNormalx;
  38569. normals[v3y] += faceNormaly;
  38570. normals[v3z] += faceNormalz;
  38571. }
  38572. // last normalization of each normal
  38573. for (index = 0; index < normals.length / 3; index++) {
  38574. faceNormalx = normals[index * 3];
  38575. faceNormaly = normals[index * 3 + 1];
  38576. faceNormalz = normals[index * 3 + 2];
  38577. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38578. length = (length === 0) ? 1.0 : length;
  38579. faceNormalx /= length;
  38580. faceNormaly /= length;
  38581. faceNormalz /= length;
  38582. normals[index * 3] = faceNormalx;
  38583. normals[index * 3 + 1] = faceNormaly;
  38584. normals[index * 3 + 2] = faceNormalz;
  38585. }
  38586. };
  38587. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38588. var li = indices.length;
  38589. var ln = normals.length;
  38590. var i;
  38591. var n;
  38592. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38593. switch (sideOrientation) {
  38594. case BABYLON.Mesh.FRONTSIDE:
  38595. // nothing changed
  38596. break;
  38597. case BABYLON.Mesh.BACKSIDE:
  38598. var tmp;
  38599. // indices
  38600. for (i = 0; i < li; i += 3) {
  38601. tmp = indices[i];
  38602. indices[i] = indices[i + 2];
  38603. indices[i + 2] = tmp;
  38604. }
  38605. // normals
  38606. for (n = 0; n < ln; n++) {
  38607. normals[n] = -normals[n];
  38608. }
  38609. break;
  38610. case BABYLON.Mesh.DOUBLESIDE:
  38611. // positions
  38612. var lp = positions.length;
  38613. var l = lp / 3;
  38614. for (var p = 0; p < lp; p++) {
  38615. positions[lp + p] = positions[p];
  38616. }
  38617. // indices
  38618. for (i = 0; i < li; i += 3) {
  38619. indices[i + li] = indices[i + 2] + l;
  38620. indices[i + 1 + li] = indices[i + 1] + l;
  38621. indices[i + 2 + li] = indices[i] + l;
  38622. }
  38623. // normals
  38624. for (n = 0; n < ln; n++) {
  38625. normals[ln + n] = -normals[n];
  38626. }
  38627. // uvs
  38628. var lu = uvs.length;
  38629. var u = 0;
  38630. for (u = 0; u < lu; u++) {
  38631. uvs[u + lu] = uvs[u];
  38632. }
  38633. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38634. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38635. u = 0;
  38636. for (i = 0; i < lu / 2; i++) {
  38637. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38638. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38639. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38640. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38641. u += 2;
  38642. }
  38643. break;
  38644. }
  38645. };
  38646. /**
  38647. * Applies VertexData created from the imported parameters to the geometry
  38648. * @param parsedVertexData the parsed data from an imported file
  38649. * @param geometry the geometry to apply the VertexData to
  38650. */
  38651. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38652. var vertexData = new VertexData();
  38653. // positions
  38654. var positions = parsedVertexData.positions;
  38655. if (positions) {
  38656. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38657. }
  38658. // normals
  38659. var normals = parsedVertexData.normals;
  38660. if (normals) {
  38661. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38662. }
  38663. // tangents
  38664. var tangents = parsedVertexData.tangents;
  38665. if (tangents) {
  38666. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38667. }
  38668. // uvs
  38669. var uvs = parsedVertexData.uvs;
  38670. if (uvs) {
  38671. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38672. }
  38673. // uv2s
  38674. var uv2s = parsedVertexData.uv2s;
  38675. if (uv2s) {
  38676. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38677. }
  38678. // uv3s
  38679. var uv3s = parsedVertexData.uv3s;
  38680. if (uv3s) {
  38681. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38682. }
  38683. // uv4s
  38684. var uv4s = parsedVertexData.uv4s;
  38685. if (uv4s) {
  38686. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38687. }
  38688. // uv5s
  38689. var uv5s = parsedVertexData.uv5s;
  38690. if (uv5s) {
  38691. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38692. }
  38693. // uv6s
  38694. var uv6s = parsedVertexData.uv6s;
  38695. if (uv6s) {
  38696. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38697. }
  38698. // colors
  38699. var colors = parsedVertexData.colors;
  38700. if (colors) {
  38701. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38702. }
  38703. // matricesIndices
  38704. var matricesIndices = parsedVertexData.matricesIndices;
  38705. if (matricesIndices) {
  38706. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38707. }
  38708. // matricesWeights
  38709. var matricesWeights = parsedVertexData.matricesWeights;
  38710. if (matricesWeights) {
  38711. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38712. }
  38713. // indices
  38714. var indices = parsedVertexData.indices;
  38715. if (indices) {
  38716. vertexData.indices = indices;
  38717. }
  38718. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38719. };
  38720. return VertexData;
  38721. }());
  38722. BABYLON.VertexData = VertexData;
  38723. })(BABYLON || (BABYLON = {}));
  38724. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38725. var BABYLON;
  38726. (function (BABYLON) {
  38727. /**
  38728. * Class used to store geometry data (vertex buffers + index buffer)
  38729. */
  38730. var Geometry = /** @class */ (function () {
  38731. /**
  38732. * Creates a new geometry
  38733. * @param id defines the unique ID
  38734. * @param scene defines the hosting scene
  38735. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38736. * @param updatable defines if geometry must be updatable (false by default)
  38737. * @param mesh defines the mesh that will be associated with the geometry
  38738. */
  38739. function Geometry(id, scene, vertexData, updatable, mesh) {
  38740. if (updatable === void 0) { updatable = false; }
  38741. if (mesh === void 0) { mesh = null; }
  38742. /**
  38743. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38744. */
  38745. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38746. this._totalVertices = 0;
  38747. this._isDisposed = false;
  38748. this._indexBufferIsUpdatable = false;
  38749. this.id = id;
  38750. this._engine = scene.getEngine();
  38751. this._meshes = [];
  38752. this._scene = scene;
  38753. //Init vertex buffer cache
  38754. this._vertexBuffers = {};
  38755. this._indices = [];
  38756. this._updatable = updatable;
  38757. // vertexData
  38758. if (vertexData) {
  38759. this.setAllVerticesData(vertexData, updatable);
  38760. }
  38761. else {
  38762. this._totalVertices = 0;
  38763. this._indices = [];
  38764. }
  38765. if (this._engine.getCaps().vertexArrayObject) {
  38766. this._vertexArrayObjects = {};
  38767. }
  38768. // applyToMesh
  38769. if (mesh) {
  38770. if (mesh.getClassName() === "LinesMesh") {
  38771. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38772. this._updateExtend();
  38773. }
  38774. this.applyToMesh(mesh);
  38775. mesh.computeWorldMatrix(true);
  38776. }
  38777. }
  38778. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38779. /**
  38780. * 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
  38781. */
  38782. get: function () {
  38783. return this._boundingBias;
  38784. },
  38785. /**
  38786. * 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
  38787. */
  38788. set: function (value) {
  38789. if (this._boundingBias && this._boundingBias.equals(value)) {
  38790. return;
  38791. }
  38792. this._boundingBias = value.clone();
  38793. this._updateBoundingInfo(true, null);
  38794. },
  38795. enumerable: true,
  38796. configurable: true
  38797. });
  38798. /**
  38799. * Static function used to attach a new empty geometry to a mesh
  38800. * @param mesh defines the mesh to attach the geometry to
  38801. * @returns the new {BABYLON.Geometry}
  38802. */
  38803. Geometry.CreateGeometryForMesh = function (mesh) {
  38804. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38805. geometry.applyToMesh(mesh);
  38806. return geometry;
  38807. };
  38808. Object.defineProperty(Geometry.prototype, "extend", {
  38809. /**
  38810. * Gets the current extend of the geometry
  38811. */
  38812. get: function () {
  38813. return this._extend;
  38814. },
  38815. enumerable: true,
  38816. configurable: true
  38817. });
  38818. /**
  38819. * Gets the hosting scene
  38820. * @returns the hosting {BABYLON.Scene}
  38821. */
  38822. Geometry.prototype.getScene = function () {
  38823. return this._scene;
  38824. };
  38825. /**
  38826. * Gets the hosting engine
  38827. * @returns the hosting {BABYLON.Engine}
  38828. */
  38829. Geometry.prototype.getEngine = function () {
  38830. return this._engine;
  38831. };
  38832. /**
  38833. * Defines if the geometry is ready to use
  38834. * @returns true if the geometry is ready to be used
  38835. */
  38836. Geometry.prototype.isReady = function () {
  38837. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38838. };
  38839. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38840. /**
  38841. * Gets a value indicating that the geometry should not be serialized
  38842. */
  38843. get: function () {
  38844. for (var index = 0; index < this._meshes.length; index++) {
  38845. if (!this._meshes[index].doNotSerialize) {
  38846. return false;
  38847. }
  38848. }
  38849. return true;
  38850. },
  38851. enumerable: true,
  38852. configurable: true
  38853. });
  38854. /** @hidden */
  38855. Geometry.prototype._rebuild = function () {
  38856. if (this._vertexArrayObjects) {
  38857. this._vertexArrayObjects = {};
  38858. }
  38859. // Index buffer
  38860. if (this._meshes.length !== 0 && this._indices) {
  38861. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38862. }
  38863. // Vertex buffers
  38864. for (var key in this._vertexBuffers) {
  38865. var vertexBuffer = this._vertexBuffers[key];
  38866. vertexBuffer._rebuild();
  38867. }
  38868. };
  38869. /**
  38870. * Affects all gemetry data in one call
  38871. * @param vertexData defines the geometry data
  38872. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38873. */
  38874. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38875. vertexData.applyToGeometry(this, updatable);
  38876. this.notifyUpdate();
  38877. };
  38878. /**
  38879. * Set specific vertex data
  38880. * @param kind defines the data kind (Position, normal, etc...)
  38881. * @param data defines the vertex data to use
  38882. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38883. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38884. */
  38885. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38886. if (updatable === void 0) { updatable = false; }
  38887. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38888. this.setVerticesBuffer(buffer);
  38889. };
  38890. /**
  38891. * Removes a specific vertex data
  38892. * @param kind defines the data kind (Position, normal, etc...)
  38893. */
  38894. Geometry.prototype.removeVerticesData = function (kind) {
  38895. if (this._vertexBuffers[kind]) {
  38896. this._vertexBuffers[kind].dispose();
  38897. delete this._vertexBuffers[kind];
  38898. }
  38899. };
  38900. /**
  38901. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38902. * @param buffer defines the vertex buffer to use
  38903. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38904. */
  38905. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38906. if (totalVertices === void 0) { totalVertices = null; }
  38907. var kind = buffer.getKind();
  38908. if (this._vertexBuffers[kind]) {
  38909. this._vertexBuffers[kind].dispose();
  38910. }
  38911. this._vertexBuffers[kind] = buffer;
  38912. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38913. var data = buffer.getData();
  38914. if (totalVertices != null) {
  38915. this._totalVertices = totalVertices;
  38916. }
  38917. else {
  38918. if (data != null) {
  38919. this._totalVertices = data.length / (buffer.byteStride / 4);
  38920. }
  38921. }
  38922. this._updateExtend(data);
  38923. this._resetPointsArrayCache();
  38924. var meshes = this._meshes;
  38925. var numOfMeshes = meshes.length;
  38926. for (var index = 0; index < numOfMeshes; index++) {
  38927. var mesh = meshes[index];
  38928. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38929. mesh._createGlobalSubMesh(false);
  38930. mesh.computeWorldMatrix(true);
  38931. }
  38932. }
  38933. this.notifyUpdate(kind);
  38934. if (this._vertexArrayObjects) {
  38935. this._disposeVertexArrayObjects();
  38936. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38937. }
  38938. };
  38939. /**
  38940. * Update a specific vertex buffer
  38941. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38942. * It will do nothing if the buffer is not updatable
  38943. * @param kind defines the data kind (Position, normal, etc...)
  38944. * @param data defines the data to use
  38945. * @param offset defines the offset in the target buffer where to store the data
  38946. * @param useBytes set to true if the offset is in bytes
  38947. */
  38948. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38949. if (useBytes === void 0) { useBytes = false; }
  38950. var vertexBuffer = this.getVertexBuffer(kind);
  38951. if (!vertexBuffer) {
  38952. return;
  38953. }
  38954. vertexBuffer.updateDirectly(data, offset, useBytes);
  38955. this.notifyUpdate(kind);
  38956. };
  38957. /**
  38958. * Update a specific vertex buffer
  38959. * This function will create a new buffer if the current one is not updatable
  38960. * @param kind defines the data kind (Position, normal, etc...)
  38961. * @param data defines the data to use
  38962. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38963. */
  38964. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38965. if (updateExtends === void 0) { updateExtends = false; }
  38966. var vertexBuffer = this.getVertexBuffer(kind);
  38967. if (!vertexBuffer) {
  38968. return;
  38969. }
  38970. vertexBuffer.update(data);
  38971. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38972. this._updateBoundingInfo(updateExtends, data);
  38973. }
  38974. this.notifyUpdate(kind);
  38975. };
  38976. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38977. if (updateExtends) {
  38978. this._updateExtend(data);
  38979. }
  38980. var meshes = this._meshes;
  38981. var numOfMeshes = meshes.length;
  38982. this._resetPointsArrayCache();
  38983. for (var index = 0; index < numOfMeshes; index++) {
  38984. var mesh = meshes[index];
  38985. if (updateExtends) {
  38986. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38987. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38988. var subMesh = mesh.subMeshes[subIndex];
  38989. subMesh.refreshBoundingInfo();
  38990. }
  38991. }
  38992. }
  38993. };
  38994. /** @hidden */
  38995. Geometry.prototype._bind = function (effect, indexToBind) {
  38996. if (!effect) {
  38997. return;
  38998. }
  38999. if (indexToBind === undefined) {
  39000. indexToBind = this._indexBuffer;
  39001. }
  39002. var vbs = this.getVertexBuffers();
  39003. if (!vbs) {
  39004. return;
  39005. }
  39006. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39007. this._engine.bindBuffers(vbs, indexToBind, effect);
  39008. return;
  39009. }
  39010. // Using VAO
  39011. if (!this._vertexArrayObjects[effect.key]) {
  39012. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39013. }
  39014. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39015. };
  39016. /**
  39017. * Gets total number of vertices
  39018. * @returns the total number of vertices
  39019. */
  39020. Geometry.prototype.getTotalVertices = function () {
  39021. if (!this.isReady()) {
  39022. return 0;
  39023. }
  39024. return this._totalVertices;
  39025. };
  39026. /**
  39027. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39028. * @param kind defines the data kind (Position, normal, etc...)
  39029. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39030. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39031. * @returns a float array containing vertex data
  39032. */
  39033. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39034. var vertexBuffer = this.getVertexBuffer(kind);
  39035. if (!vertexBuffer) {
  39036. return null;
  39037. }
  39038. var data = vertexBuffer.getData();
  39039. if (!data) {
  39040. return null;
  39041. }
  39042. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39043. var count = this._totalVertices * vertexBuffer.getSize();
  39044. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39045. var copy_1 = new Array(count);
  39046. vertexBuffer.forEach(count, function (value, index) {
  39047. copy_1[index] = value;
  39048. });
  39049. return copy_1;
  39050. }
  39051. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39052. if (data instanceof Array) {
  39053. var offset = vertexBuffer.byteOffset / 4;
  39054. return BABYLON.Tools.Slice(data, offset, offset + count);
  39055. }
  39056. else if (data instanceof ArrayBuffer) {
  39057. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39058. }
  39059. else {
  39060. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39061. }
  39062. }
  39063. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39064. return BABYLON.Tools.Slice(data);
  39065. }
  39066. return data;
  39067. };
  39068. /**
  39069. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39070. * @param kind defines the data kind (Position, normal, etc...)
  39071. * @returns true if the vertex buffer with the specified kind is updatable
  39072. */
  39073. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39074. var vb = this._vertexBuffers[kind];
  39075. if (!vb) {
  39076. return false;
  39077. }
  39078. return vb.isUpdatable();
  39079. };
  39080. /**
  39081. * Gets a specific vertex buffer
  39082. * @param kind defines the data kind (Position, normal, etc...)
  39083. * @returns a {BABYLON.VertexBuffer}
  39084. */
  39085. Geometry.prototype.getVertexBuffer = function (kind) {
  39086. if (!this.isReady()) {
  39087. return null;
  39088. }
  39089. return this._vertexBuffers[kind];
  39090. };
  39091. /**
  39092. * Returns all vertex buffers
  39093. * @return an object holding all vertex buffers indexed by kind
  39094. */
  39095. Geometry.prototype.getVertexBuffers = function () {
  39096. if (!this.isReady()) {
  39097. return null;
  39098. }
  39099. return this._vertexBuffers;
  39100. };
  39101. /**
  39102. * Gets a boolean indicating if specific vertex buffer is present
  39103. * @param kind defines the data kind (Position, normal, etc...)
  39104. * @returns true if data is present
  39105. */
  39106. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39107. if (!this._vertexBuffers) {
  39108. if (this._delayInfo) {
  39109. return this._delayInfo.indexOf(kind) !== -1;
  39110. }
  39111. return false;
  39112. }
  39113. return this._vertexBuffers[kind] !== undefined;
  39114. };
  39115. /**
  39116. * Gets a list of all attached data kinds (Position, normal, etc...)
  39117. * @returns a list of string containing all kinds
  39118. */
  39119. Geometry.prototype.getVerticesDataKinds = function () {
  39120. var result = [];
  39121. var kind;
  39122. if (!this._vertexBuffers && this._delayInfo) {
  39123. for (kind in this._delayInfo) {
  39124. result.push(kind);
  39125. }
  39126. }
  39127. else {
  39128. for (kind in this._vertexBuffers) {
  39129. result.push(kind);
  39130. }
  39131. }
  39132. return result;
  39133. };
  39134. /**
  39135. * Update index buffer
  39136. * @param indices defines the indices to store in the index buffer
  39137. * @param offset defines the offset in the target buffer where to store the data
  39138. */
  39139. Geometry.prototype.updateIndices = function (indices, offset) {
  39140. if (!this._indexBuffer) {
  39141. return;
  39142. }
  39143. if (!this._indexBufferIsUpdatable) {
  39144. this.setIndices(indices, null, true);
  39145. }
  39146. else {
  39147. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39148. }
  39149. };
  39150. /**
  39151. * Creates a new index buffer
  39152. * @param indices defines the indices to store in the index buffer
  39153. * @param totalVertices defines the total number of vertices (could be null)
  39154. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39155. */
  39156. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39157. if (totalVertices === void 0) { totalVertices = null; }
  39158. if (updatable === void 0) { updatable = false; }
  39159. if (this._indexBuffer) {
  39160. this._engine._releaseBuffer(this._indexBuffer);
  39161. }
  39162. this._disposeVertexArrayObjects();
  39163. this._indices = indices;
  39164. this._indexBufferIsUpdatable = updatable;
  39165. if (this._meshes.length !== 0 && this._indices) {
  39166. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39167. }
  39168. if (totalVertices != undefined) { // including null and undefined
  39169. this._totalVertices = totalVertices;
  39170. }
  39171. var meshes = this._meshes;
  39172. var numOfMeshes = meshes.length;
  39173. for (var index = 0; index < numOfMeshes; index++) {
  39174. meshes[index]._createGlobalSubMesh(true);
  39175. }
  39176. this.notifyUpdate();
  39177. };
  39178. /**
  39179. * Return the total number of indices
  39180. * @returns the total number of indices
  39181. */
  39182. Geometry.prototype.getTotalIndices = function () {
  39183. if (!this.isReady()) {
  39184. return 0;
  39185. }
  39186. return this._indices.length;
  39187. };
  39188. /**
  39189. * Gets the index buffer array
  39190. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39191. * @returns the index buffer array
  39192. */
  39193. Geometry.prototype.getIndices = function (copyWhenShared) {
  39194. if (!this.isReady()) {
  39195. return null;
  39196. }
  39197. var orig = this._indices;
  39198. if (!copyWhenShared || this._meshes.length === 1) {
  39199. return orig;
  39200. }
  39201. else {
  39202. var len = orig.length;
  39203. var copy = [];
  39204. for (var i = 0; i < len; i++) {
  39205. copy.push(orig[i]);
  39206. }
  39207. return copy;
  39208. }
  39209. };
  39210. /**
  39211. * Gets the index buffer
  39212. * @return the index buffer
  39213. */
  39214. Geometry.prototype.getIndexBuffer = function () {
  39215. if (!this.isReady()) {
  39216. return null;
  39217. }
  39218. return this._indexBuffer;
  39219. };
  39220. /** @hidden */
  39221. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39222. if (effect === void 0) { effect = null; }
  39223. if (!effect || !this._vertexArrayObjects) {
  39224. return;
  39225. }
  39226. if (this._vertexArrayObjects[effect.key]) {
  39227. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39228. delete this._vertexArrayObjects[effect.key];
  39229. }
  39230. };
  39231. /**
  39232. * Release the associated resources for a specific mesh
  39233. * @param mesh defines the source mesh
  39234. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39235. */
  39236. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39237. var meshes = this._meshes;
  39238. var index = meshes.indexOf(mesh);
  39239. if (index === -1) {
  39240. return;
  39241. }
  39242. meshes.splice(index, 1);
  39243. mesh._geometry = null;
  39244. if (meshes.length === 0 && shouldDispose) {
  39245. this.dispose();
  39246. }
  39247. };
  39248. /**
  39249. * Apply current geometry to a given mesh
  39250. * @param mesh defines the mesh to apply geometry to
  39251. */
  39252. Geometry.prototype.applyToMesh = function (mesh) {
  39253. if (mesh._geometry === this) {
  39254. return;
  39255. }
  39256. var previousGeometry = mesh._geometry;
  39257. if (previousGeometry) {
  39258. previousGeometry.releaseForMesh(mesh);
  39259. }
  39260. var meshes = this._meshes;
  39261. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39262. mesh._geometry = this;
  39263. this._scene.pushGeometry(this);
  39264. meshes.push(mesh);
  39265. if (this.isReady()) {
  39266. this._applyToMesh(mesh);
  39267. }
  39268. else {
  39269. mesh._boundingInfo = this._boundingInfo;
  39270. }
  39271. };
  39272. Geometry.prototype._updateExtend = function (data) {
  39273. if (data === void 0) { data = null; }
  39274. if (!data) {
  39275. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39276. }
  39277. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39278. };
  39279. Geometry.prototype._applyToMesh = function (mesh) {
  39280. var numOfMeshes = this._meshes.length;
  39281. // vertexBuffers
  39282. for (var kind in this._vertexBuffers) {
  39283. if (numOfMeshes === 1) {
  39284. this._vertexBuffers[kind].create();
  39285. }
  39286. var buffer = this._vertexBuffers[kind].getBuffer();
  39287. if (buffer)
  39288. buffer.references = numOfMeshes;
  39289. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39290. if (!this._extend) {
  39291. this._updateExtend();
  39292. }
  39293. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39294. mesh._createGlobalSubMesh(false);
  39295. //bounding info was just created again, world matrix should be applied again.
  39296. mesh._updateBoundingInfo();
  39297. }
  39298. }
  39299. // indexBuffer
  39300. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39301. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39302. }
  39303. if (this._indexBuffer) {
  39304. this._indexBuffer.references = numOfMeshes;
  39305. }
  39306. };
  39307. Geometry.prototype.notifyUpdate = function (kind) {
  39308. if (this.onGeometryUpdated) {
  39309. this.onGeometryUpdated(this, kind);
  39310. }
  39311. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39312. var mesh = _a[_i];
  39313. mesh._markSubMeshesAsAttributesDirty();
  39314. }
  39315. };
  39316. /**
  39317. * Load the geometry if it was flagged as delay loaded
  39318. * @param scene defines the hosting scene
  39319. * @param onLoaded defines a callback called when the geometry is loaded
  39320. */
  39321. Geometry.prototype.load = function (scene, onLoaded) {
  39322. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39323. return;
  39324. }
  39325. if (this.isReady()) {
  39326. if (onLoaded) {
  39327. onLoaded();
  39328. }
  39329. return;
  39330. }
  39331. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39332. this._queueLoad(scene, onLoaded);
  39333. };
  39334. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39335. var _this = this;
  39336. if (!this.delayLoadingFile) {
  39337. return;
  39338. }
  39339. scene._addPendingData(this);
  39340. scene._loadFile(this.delayLoadingFile, function (data) {
  39341. if (!_this._delayLoadingFunction) {
  39342. return;
  39343. }
  39344. _this._delayLoadingFunction(JSON.parse(data), _this);
  39345. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39346. _this._delayInfo = [];
  39347. scene._removePendingData(_this);
  39348. var meshes = _this._meshes;
  39349. var numOfMeshes = meshes.length;
  39350. for (var index = 0; index < numOfMeshes; index++) {
  39351. _this._applyToMesh(meshes[index]);
  39352. }
  39353. if (onLoaded) {
  39354. onLoaded();
  39355. }
  39356. }, undefined, true);
  39357. };
  39358. /**
  39359. * Invert the geometry to move from a right handed system to a left handed one.
  39360. */
  39361. Geometry.prototype.toLeftHanded = function () {
  39362. // Flip faces
  39363. var tIndices = this.getIndices(false);
  39364. if (tIndices != null && tIndices.length > 0) {
  39365. for (var i = 0; i < tIndices.length; i += 3) {
  39366. var tTemp = tIndices[i + 0];
  39367. tIndices[i + 0] = tIndices[i + 2];
  39368. tIndices[i + 2] = tTemp;
  39369. }
  39370. this.setIndices(tIndices);
  39371. }
  39372. // Negate position.z
  39373. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39374. if (tPositions != null && tPositions.length > 0) {
  39375. for (var i = 0; i < tPositions.length; i += 3) {
  39376. tPositions[i + 2] = -tPositions[i + 2];
  39377. }
  39378. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39379. }
  39380. // Negate normal.z
  39381. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39382. if (tNormals != null && tNormals.length > 0) {
  39383. for (var i = 0; i < tNormals.length; i += 3) {
  39384. tNormals[i + 2] = -tNormals[i + 2];
  39385. }
  39386. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39387. }
  39388. };
  39389. // Cache
  39390. /** @hidden */
  39391. Geometry.prototype._resetPointsArrayCache = function () {
  39392. this._positions = null;
  39393. };
  39394. /** @hidden */
  39395. Geometry.prototype._generatePointsArray = function () {
  39396. if (this._positions)
  39397. return true;
  39398. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39399. if (!data || data.length === 0) {
  39400. return false;
  39401. }
  39402. this._positions = [];
  39403. for (var index = 0; index < data.length; index += 3) {
  39404. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39405. }
  39406. return true;
  39407. };
  39408. /**
  39409. * Gets a value indicating if the geometry is disposed
  39410. * @returns true if the geometry was disposed
  39411. */
  39412. Geometry.prototype.isDisposed = function () {
  39413. return this._isDisposed;
  39414. };
  39415. Geometry.prototype._disposeVertexArrayObjects = function () {
  39416. if (this._vertexArrayObjects) {
  39417. for (var kind in this._vertexArrayObjects) {
  39418. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39419. }
  39420. this._vertexArrayObjects = {};
  39421. }
  39422. };
  39423. /**
  39424. * Free all associated resources
  39425. */
  39426. Geometry.prototype.dispose = function () {
  39427. var meshes = this._meshes;
  39428. var numOfMeshes = meshes.length;
  39429. var index;
  39430. for (index = 0; index < numOfMeshes; index++) {
  39431. this.releaseForMesh(meshes[index]);
  39432. }
  39433. this._meshes = [];
  39434. this._disposeVertexArrayObjects();
  39435. for (var kind in this._vertexBuffers) {
  39436. this._vertexBuffers[kind].dispose();
  39437. }
  39438. this._vertexBuffers = {};
  39439. this._totalVertices = 0;
  39440. if (this._indexBuffer) {
  39441. this._engine._releaseBuffer(this._indexBuffer);
  39442. }
  39443. this._indexBuffer = null;
  39444. this._indices = [];
  39445. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39446. this.delayLoadingFile = null;
  39447. this._delayLoadingFunction = null;
  39448. this._delayInfo = [];
  39449. this._boundingInfo = null;
  39450. this._scene.removeGeometry(this);
  39451. this._isDisposed = true;
  39452. };
  39453. /**
  39454. * Clone the current geometry into a new geometry
  39455. * @param id defines the unique ID of the new geometry
  39456. * @returns a new geometry object
  39457. */
  39458. Geometry.prototype.copy = function (id) {
  39459. var vertexData = new BABYLON.VertexData();
  39460. vertexData.indices = [];
  39461. var indices = this.getIndices();
  39462. if (indices) {
  39463. for (var index = 0; index < indices.length; index++) {
  39464. vertexData.indices.push(indices[index]);
  39465. }
  39466. }
  39467. var updatable = false;
  39468. var stopChecking = false;
  39469. var kind;
  39470. for (kind in this._vertexBuffers) {
  39471. // using slice() to make a copy of the array and not just reference it
  39472. var data = this.getVerticesData(kind);
  39473. if (data instanceof Float32Array) {
  39474. vertexData.set(new Float32Array(data), kind);
  39475. }
  39476. else {
  39477. vertexData.set(data.slice(0), kind);
  39478. }
  39479. if (!stopChecking) {
  39480. var vb = this.getVertexBuffer(kind);
  39481. if (vb) {
  39482. updatable = vb.isUpdatable();
  39483. stopChecking = !updatable;
  39484. }
  39485. }
  39486. }
  39487. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39488. geometry.delayLoadState = this.delayLoadState;
  39489. geometry.delayLoadingFile = this.delayLoadingFile;
  39490. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39491. for (kind in this._delayInfo) {
  39492. geometry._delayInfo = geometry._delayInfo || [];
  39493. geometry._delayInfo.push(kind);
  39494. }
  39495. // Bounding info
  39496. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39497. return geometry;
  39498. };
  39499. /**
  39500. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39501. * @return a JSON representation of the current geometry data (without the vertices data)
  39502. */
  39503. Geometry.prototype.serialize = function () {
  39504. var serializationObject = {};
  39505. serializationObject.id = this.id;
  39506. serializationObject.updatable = this._updatable;
  39507. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39508. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39509. }
  39510. return serializationObject;
  39511. };
  39512. Geometry.prototype.toNumberArray = function (origin) {
  39513. if (Array.isArray(origin)) {
  39514. return origin;
  39515. }
  39516. else {
  39517. return Array.prototype.slice.call(origin);
  39518. }
  39519. };
  39520. /**
  39521. * Serialize all vertices data into a JSON oject
  39522. * @returns a JSON representation of the current geometry data
  39523. */
  39524. Geometry.prototype.serializeVerticeData = function () {
  39525. var serializationObject = this.serialize();
  39526. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39527. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39528. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39529. serializationObject.positions._updatable = true;
  39530. }
  39531. }
  39532. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39533. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39534. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39535. serializationObject.normals._updatable = true;
  39536. }
  39537. }
  39538. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39539. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39540. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39541. serializationObject.tangets._updatable = true;
  39542. }
  39543. }
  39544. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39545. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39546. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39547. serializationObject.uvs._updatable = true;
  39548. }
  39549. }
  39550. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39551. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39552. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39553. serializationObject.uv2s._updatable = true;
  39554. }
  39555. }
  39556. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39557. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39558. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39559. serializationObject.uv3s._updatable = true;
  39560. }
  39561. }
  39562. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39563. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39564. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39565. serializationObject.uv4s._updatable = true;
  39566. }
  39567. }
  39568. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39569. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39570. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39571. serializationObject.uv5s._updatable = true;
  39572. }
  39573. }
  39574. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39575. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39576. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39577. serializationObject.uv6s._updatable = true;
  39578. }
  39579. }
  39580. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39581. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39582. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39583. serializationObject.colors._updatable = true;
  39584. }
  39585. }
  39586. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39587. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39588. serializationObject.matricesIndices._isExpanded = true;
  39589. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39590. serializationObject.matricesIndices._updatable = true;
  39591. }
  39592. }
  39593. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39594. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39595. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39596. serializationObject.matricesWeights._updatable = true;
  39597. }
  39598. }
  39599. serializationObject.indices = this.toNumberArray(this.getIndices());
  39600. return serializationObject;
  39601. };
  39602. // Statics
  39603. /**
  39604. * Extracts a clone of a mesh geometry
  39605. * @param mesh defines the source mesh
  39606. * @param id defines the unique ID of the new geometry object
  39607. * @returns the new geometry object
  39608. */
  39609. Geometry.ExtractFromMesh = function (mesh, id) {
  39610. var geometry = mesh._geometry;
  39611. if (!geometry) {
  39612. return null;
  39613. }
  39614. return geometry.copy(id);
  39615. };
  39616. /**
  39617. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39618. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39619. * Be aware Math.random() could cause collisions, but:
  39620. * "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"
  39621. * @returns a string containing a new GUID
  39622. */
  39623. Geometry.RandomId = function () {
  39624. return BABYLON.Tools.RandomId();
  39625. };
  39626. /** @hidden */
  39627. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39628. var scene = mesh.getScene();
  39629. // Geometry
  39630. var geometryId = parsedGeometry.geometryId;
  39631. if (geometryId) {
  39632. var geometry = scene.getGeometryByID(geometryId);
  39633. if (geometry) {
  39634. geometry.applyToMesh(mesh);
  39635. }
  39636. }
  39637. else if (parsedGeometry instanceof ArrayBuffer) {
  39638. var binaryInfo = mesh._binaryInfo;
  39639. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39640. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39641. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39642. }
  39643. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39644. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39645. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39646. }
  39647. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39648. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39649. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39650. }
  39651. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39652. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39653. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39654. }
  39655. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39656. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39657. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39658. }
  39659. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39660. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39661. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39662. }
  39663. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39664. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39665. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39666. }
  39667. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39668. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39669. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39670. }
  39671. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39672. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39673. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39674. }
  39675. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39676. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39677. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39678. }
  39679. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39680. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39681. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39682. }
  39683. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39684. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39685. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39686. }
  39687. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39688. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39689. mesh.setIndices(indicesData, null);
  39690. }
  39691. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39692. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39693. mesh.subMeshes = [];
  39694. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39695. var materialIndex = subMeshesData[(i * 5) + 0];
  39696. var verticesStart = subMeshesData[(i * 5) + 1];
  39697. var verticesCount = subMeshesData[(i * 5) + 2];
  39698. var indexStart = subMeshesData[(i * 5) + 3];
  39699. var indexCount = subMeshesData[(i * 5) + 4];
  39700. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39701. }
  39702. }
  39703. }
  39704. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39705. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39706. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39707. if (parsedGeometry.tangents) {
  39708. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39709. }
  39710. if (parsedGeometry.uvs) {
  39711. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39712. }
  39713. if (parsedGeometry.uvs2) {
  39714. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39715. }
  39716. if (parsedGeometry.uvs3) {
  39717. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39718. }
  39719. if (parsedGeometry.uvs4) {
  39720. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39721. }
  39722. if (parsedGeometry.uvs5) {
  39723. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39724. }
  39725. if (parsedGeometry.uvs6) {
  39726. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39727. }
  39728. if (parsedGeometry.colors) {
  39729. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39730. }
  39731. if (parsedGeometry.matricesIndices) {
  39732. if (!parsedGeometry.matricesIndices._isExpanded) {
  39733. var floatIndices = [];
  39734. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39735. var matricesIndex = parsedGeometry.matricesIndices[i];
  39736. floatIndices.push(matricesIndex & 0x000000FF);
  39737. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39738. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39739. floatIndices.push(matricesIndex >> 24);
  39740. }
  39741. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39742. }
  39743. else {
  39744. delete parsedGeometry.matricesIndices._isExpanded;
  39745. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39746. }
  39747. }
  39748. if (parsedGeometry.matricesIndicesExtra) {
  39749. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39750. var floatIndices = [];
  39751. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39752. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39753. floatIndices.push(matricesIndex & 0x000000FF);
  39754. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39755. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39756. floatIndices.push(matricesIndex >> 24);
  39757. }
  39758. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39759. }
  39760. else {
  39761. delete parsedGeometry.matricesIndices._isExpanded;
  39762. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39763. }
  39764. }
  39765. if (parsedGeometry.matricesWeights) {
  39766. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39767. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39768. }
  39769. if (parsedGeometry.matricesWeightsExtra) {
  39770. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39771. }
  39772. mesh.setIndices(parsedGeometry.indices, null);
  39773. }
  39774. // SubMeshes
  39775. if (parsedGeometry.subMeshes) {
  39776. mesh.subMeshes = [];
  39777. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39778. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39779. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39780. }
  39781. }
  39782. // Flat shading
  39783. if (mesh._shouldGenerateFlatShading) {
  39784. mesh.convertToFlatShadedMesh();
  39785. delete mesh._shouldGenerateFlatShading;
  39786. }
  39787. // Update
  39788. mesh.computeWorldMatrix(true);
  39789. // Octree
  39790. var sceneOctree = scene.selectionOctree;
  39791. if (sceneOctree !== undefined && sceneOctree !== null) {
  39792. sceneOctree.addMesh(mesh);
  39793. }
  39794. };
  39795. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39796. var epsilon = 1e-3;
  39797. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39798. return;
  39799. }
  39800. var noInfluenceBoneIndex = 0.0;
  39801. if (parsedGeometry.skeletonId > -1) {
  39802. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39803. if (!skeleton) {
  39804. return;
  39805. }
  39806. noInfluenceBoneIndex = skeleton.bones.length;
  39807. }
  39808. else {
  39809. return;
  39810. }
  39811. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39812. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39813. var matricesWeights = parsedGeometry.matricesWeights;
  39814. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39815. var influencers = parsedGeometry.numBoneInfluencer;
  39816. var size = matricesWeights.length;
  39817. for (var i = 0; i < size; i += 4) {
  39818. var weight = 0.0;
  39819. var firstZeroWeight = -1;
  39820. for (var j = 0; j < 4; j++) {
  39821. var w = matricesWeights[i + j];
  39822. weight += w;
  39823. if (w < epsilon && firstZeroWeight < 0) {
  39824. firstZeroWeight = j;
  39825. }
  39826. }
  39827. if (matricesWeightsExtra) {
  39828. for (var j = 0; j < 4; j++) {
  39829. var w = matricesWeightsExtra[i + j];
  39830. weight += w;
  39831. if (w < epsilon && firstZeroWeight < 0) {
  39832. firstZeroWeight = j + 4;
  39833. }
  39834. }
  39835. }
  39836. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39837. firstZeroWeight = influencers - 1;
  39838. }
  39839. if (weight > epsilon) {
  39840. var mweight = 1.0 / weight;
  39841. for (var j = 0; j < 4; j++) {
  39842. matricesWeights[i + j] *= mweight;
  39843. }
  39844. if (matricesWeightsExtra) {
  39845. for (var j = 0; j < 4; j++) {
  39846. matricesWeightsExtra[i + j] *= mweight;
  39847. }
  39848. }
  39849. }
  39850. else {
  39851. if (firstZeroWeight >= 4) {
  39852. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39853. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39854. }
  39855. else {
  39856. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39857. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39858. }
  39859. }
  39860. }
  39861. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39862. if (parsedGeometry.matricesWeightsExtra) {
  39863. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39864. }
  39865. };
  39866. /**
  39867. * Create a new geometry from persisted data (Using .babylon file format)
  39868. * @param parsedVertexData defines the persisted data
  39869. * @param scene defines the hosting scene
  39870. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39871. * @returns the new geometry object
  39872. */
  39873. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39874. if (scene.getGeometryByID(parsedVertexData.id)) {
  39875. return null; // null since geometry could be something else than a box...
  39876. }
  39877. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39878. if (BABYLON.Tags) {
  39879. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39880. }
  39881. if (parsedVertexData.delayLoadingFile) {
  39882. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39883. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39884. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39885. geometry._delayInfo = [];
  39886. if (parsedVertexData.hasUVs) {
  39887. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39888. }
  39889. if (parsedVertexData.hasUVs2) {
  39890. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39891. }
  39892. if (parsedVertexData.hasUVs3) {
  39893. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39894. }
  39895. if (parsedVertexData.hasUVs4) {
  39896. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39897. }
  39898. if (parsedVertexData.hasUVs5) {
  39899. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39900. }
  39901. if (parsedVertexData.hasUVs6) {
  39902. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39903. }
  39904. if (parsedVertexData.hasColors) {
  39905. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39906. }
  39907. if (parsedVertexData.hasMatricesIndices) {
  39908. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39909. }
  39910. if (parsedVertexData.hasMatricesWeights) {
  39911. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39912. }
  39913. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39914. }
  39915. else {
  39916. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39917. }
  39918. scene.pushGeometry(geometry, true);
  39919. return geometry;
  39920. };
  39921. return Geometry;
  39922. }());
  39923. BABYLON.Geometry = Geometry;
  39924. // Primitives
  39925. /// Abstract class
  39926. /**
  39927. * Abstract class used to provide common services for all typed geometries
  39928. * @hidden
  39929. */
  39930. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39931. __extends(_PrimitiveGeometry, _super);
  39932. /**
  39933. * Creates a new typed geometry
  39934. * @param id defines the unique ID of the geometry
  39935. * @param scene defines the hosting scene
  39936. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39937. * @param mesh defines the hosting mesh (can be null)
  39938. */
  39939. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39940. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39941. if (mesh === void 0) { mesh = null; }
  39942. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39943. _this._canBeRegenerated = _canBeRegenerated;
  39944. _this._beingRegenerated = true;
  39945. _this.regenerate();
  39946. _this._beingRegenerated = false;
  39947. return _this;
  39948. }
  39949. /**
  39950. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39951. * @returns true if the geometry can be regenerated
  39952. */
  39953. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39954. return this._canBeRegenerated;
  39955. };
  39956. /**
  39957. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39958. */
  39959. _PrimitiveGeometry.prototype.regenerate = function () {
  39960. if (!this._canBeRegenerated) {
  39961. return;
  39962. }
  39963. this._beingRegenerated = true;
  39964. this.setAllVerticesData(this._regenerateVertexData(), false);
  39965. this._beingRegenerated = false;
  39966. };
  39967. /**
  39968. * Clone the geometry
  39969. * @param id defines the unique ID of the new geometry
  39970. * @returns the new geometry
  39971. */
  39972. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39973. return _super.prototype.copy.call(this, id);
  39974. };
  39975. // overrides
  39976. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39977. if (!this._beingRegenerated) {
  39978. return;
  39979. }
  39980. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39981. };
  39982. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39983. if (!this._beingRegenerated) {
  39984. return;
  39985. }
  39986. _super.prototype.setVerticesData.call(this, kind, data, false);
  39987. };
  39988. // to override
  39989. /** @hidden */
  39990. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39991. throw new Error("Abstract method");
  39992. };
  39993. _PrimitiveGeometry.prototype.copy = function (id) {
  39994. throw new Error("Must be overriden in sub-classes.");
  39995. };
  39996. _PrimitiveGeometry.prototype.serialize = function () {
  39997. var serializationObject = _super.prototype.serialize.call(this);
  39998. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39999. return serializationObject;
  40000. };
  40001. return _PrimitiveGeometry;
  40002. }(Geometry));
  40003. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40004. /**
  40005. * Creates a ribbon geometry
  40006. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40007. */
  40008. var RibbonGeometry = /** @class */ (function (_super) {
  40009. __extends(RibbonGeometry, _super);
  40010. /**
  40011. * Creates a ribbon geometry
  40012. * @param id defines the unique ID of the geometry
  40013. * @param scene defines the hosting scene
  40014. * @param pathArray defines the array of paths to use
  40015. * @param closeArray defines if the last path and the first path must be joined
  40016. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40017. * @param offset defines the offset between points
  40018. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40019. * @param mesh defines the hosting mesh (can be null)
  40020. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40021. */
  40022. function RibbonGeometry(id, scene,
  40023. /**
  40024. * Defines the array of paths to use
  40025. */
  40026. pathArray,
  40027. /**
  40028. * Defines if the last and first points of each path in your pathArray must be joined
  40029. */
  40030. closeArray,
  40031. /**
  40032. * Defines if the last and first points of each path in your pathArray must be joined
  40033. */
  40034. closePath,
  40035. /**
  40036. * Defines the offset between points
  40037. */
  40038. offset, canBeRegenerated, mesh,
  40039. /**
  40040. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40041. */
  40042. side) {
  40043. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40044. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40045. _this.pathArray = pathArray;
  40046. _this.closeArray = closeArray;
  40047. _this.closePath = closePath;
  40048. _this.offset = offset;
  40049. _this.side = side;
  40050. return _this;
  40051. }
  40052. /** @hidden */
  40053. RibbonGeometry.prototype._regenerateVertexData = function () {
  40054. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40055. };
  40056. RibbonGeometry.prototype.copy = function (id) {
  40057. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40058. };
  40059. return RibbonGeometry;
  40060. }(_PrimitiveGeometry));
  40061. BABYLON.RibbonGeometry = RibbonGeometry;
  40062. /**
  40063. * Creates a box geometry
  40064. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40065. */
  40066. var BoxGeometry = /** @class */ (function (_super) {
  40067. __extends(BoxGeometry, _super);
  40068. /**
  40069. * Creates a box geometry
  40070. * @param id defines the unique ID of the geometry
  40071. * @param scene defines the hosting scene
  40072. * @param size defines the zise of the box (width, height and depth are the same)
  40073. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40074. * @param mesh defines the hosting mesh (can be null)
  40075. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40076. */
  40077. function BoxGeometry(id, scene,
  40078. /**
  40079. * Defines the zise of the box (width, height and depth are the same)
  40080. */
  40081. size, canBeRegenerated, mesh,
  40082. /**
  40083. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40084. */
  40085. side) {
  40086. if (mesh === void 0) { mesh = null; }
  40087. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40088. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40089. _this.size = size;
  40090. _this.side = side;
  40091. return _this;
  40092. }
  40093. BoxGeometry.prototype._regenerateVertexData = function () {
  40094. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40095. };
  40096. BoxGeometry.prototype.copy = function (id) {
  40097. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40098. };
  40099. BoxGeometry.prototype.serialize = function () {
  40100. var serializationObject = _super.prototype.serialize.call(this);
  40101. serializationObject.size = this.size;
  40102. return serializationObject;
  40103. };
  40104. BoxGeometry.Parse = function (parsedBox, scene) {
  40105. if (scene.getGeometryByID(parsedBox.id)) {
  40106. return null; // null since geometry could be something else than a box...
  40107. }
  40108. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40109. if (BABYLON.Tags) {
  40110. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40111. }
  40112. scene.pushGeometry(box, true);
  40113. return box;
  40114. };
  40115. return BoxGeometry;
  40116. }(_PrimitiveGeometry));
  40117. BABYLON.BoxGeometry = BoxGeometry;
  40118. /**
  40119. * Creates a sphere geometry
  40120. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40121. */
  40122. var SphereGeometry = /** @class */ (function (_super) {
  40123. __extends(SphereGeometry, _super);
  40124. /**
  40125. * Create a new sphere geometry
  40126. * @param id defines the unique ID of the geometry
  40127. * @param scene defines the hosting scene
  40128. * @param segments defines the number of segments to use to create the sphere
  40129. * @param diameter defines the diameter of the sphere
  40130. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40131. * @param mesh defines the hosting mesh (can be null)
  40132. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40133. */
  40134. function SphereGeometry(id, scene,
  40135. /**
  40136. * Defines the number of segments to use to create the sphere
  40137. */
  40138. segments,
  40139. /**
  40140. * Defines the diameter of the sphere
  40141. */
  40142. diameter, canBeRegenerated, mesh,
  40143. /**
  40144. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40145. */
  40146. side) {
  40147. if (mesh === void 0) { mesh = null; }
  40148. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40149. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40150. _this.segments = segments;
  40151. _this.diameter = diameter;
  40152. _this.side = side;
  40153. return _this;
  40154. }
  40155. SphereGeometry.prototype._regenerateVertexData = function () {
  40156. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40157. };
  40158. SphereGeometry.prototype.copy = function (id) {
  40159. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40160. };
  40161. SphereGeometry.prototype.serialize = function () {
  40162. var serializationObject = _super.prototype.serialize.call(this);
  40163. serializationObject.segments = this.segments;
  40164. serializationObject.diameter = this.diameter;
  40165. return serializationObject;
  40166. };
  40167. SphereGeometry.Parse = function (parsedSphere, scene) {
  40168. if (scene.getGeometryByID(parsedSphere.id)) {
  40169. return null; // null since geometry could be something else than a sphere...
  40170. }
  40171. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40172. if (BABYLON.Tags) {
  40173. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40174. }
  40175. scene.pushGeometry(sphere, true);
  40176. return sphere;
  40177. };
  40178. return SphereGeometry;
  40179. }(_PrimitiveGeometry));
  40180. BABYLON.SphereGeometry = SphereGeometry;
  40181. /**
  40182. * Creates a disc geometry
  40183. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40184. */
  40185. var DiscGeometry = /** @class */ (function (_super) {
  40186. __extends(DiscGeometry, _super);
  40187. /**
  40188. * Creates a new disc geometry
  40189. * @param id defines the unique ID of the geometry
  40190. * @param scene defines the hosting scene
  40191. * @param radius defines the radius of the disc
  40192. * @param tessellation defines the tesselation factor to apply to the disc
  40193. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40194. * @param mesh defines the hosting mesh (can be null)
  40195. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40196. */
  40197. function DiscGeometry(id, scene,
  40198. /**
  40199. * Defines the radius of the disc
  40200. */
  40201. radius,
  40202. /**
  40203. * Defines the tesselation factor to apply to the disc
  40204. */
  40205. tessellation, canBeRegenerated, mesh,
  40206. /**
  40207. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40208. */
  40209. side) {
  40210. if (mesh === void 0) { mesh = null; }
  40211. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40212. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40213. _this.radius = radius;
  40214. _this.tessellation = tessellation;
  40215. _this.side = side;
  40216. return _this;
  40217. }
  40218. DiscGeometry.prototype._regenerateVertexData = function () {
  40219. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40220. };
  40221. DiscGeometry.prototype.copy = function (id) {
  40222. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40223. };
  40224. return DiscGeometry;
  40225. }(_PrimitiveGeometry));
  40226. BABYLON.DiscGeometry = DiscGeometry;
  40227. /**
  40228. * Creates a new cylinder geometry
  40229. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40230. */
  40231. var CylinderGeometry = /** @class */ (function (_super) {
  40232. __extends(CylinderGeometry, _super);
  40233. /**
  40234. * Creates a new cylinder geometry
  40235. * @param id defines the unique ID of the geometry
  40236. * @param scene defines the hosting scene
  40237. * @param height defines the height of the cylinder
  40238. * @param diameterTop defines the diameter of the cylinder's top cap
  40239. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40240. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40241. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40242. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40243. * @param mesh defines the hosting mesh (can be null)
  40244. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40245. */
  40246. function CylinderGeometry(id, scene,
  40247. /**
  40248. * Defines the height of the cylinder
  40249. */
  40250. height,
  40251. /**
  40252. * Defines the diameter of the cylinder's top cap
  40253. */
  40254. diameterTop,
  40255. /**
  40256. * Defines the diameter of the cylinder's bottom cap
  40257. */
  40258. diameterBottom,
  40259. /**
  40260. * Defines the tessellation factor to apply to the cylinder
  40261. */
  40262. tessellation,
  40263. /**
  40264. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40265. */
  40266. subdivisions, canBeRegenerated, mesh,
  40267. /**
  40268. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40269. */
  40270. side) {
  40271. if (subdivisions === void 0) { subdivisions = 1; }
  40272. if (mesh === void 0) { mesh = null; }
  40273. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40274. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40275. _this.height = height;
  40276. _this.diameterTop = diameterTop;
  40277. _this.diameterBottom = diameterBottom;
  40278. _this.tessellation = tessellation;
  40279. _this.subdivisions = subdivisions;
  40280. _this.side = side;
  40281. return _this;
  40282. }
  40283. CylinderGeometry.prototype._regenerateVertexData = function () {
  40284. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40285. };
  40286. CylinderGeometry.prototype.copy = function (id) {
  40287. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40288. };
  40289. CylinderGeometry.prototype.serialize = function () {
  40290. var serializationObject = _super.prototype.serialize.call(this);
  40291. serializationObject.height = this.height;
  40292. serializationObject.diameterTop = this.diameterTop;
  40293. serializationObject.diameterBottom = this.diameterBottom;
  40294. serializationObject.tessellation = this.tessellation;
  40295. return serializationObject;
  40296. };
  40297. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40298. if (scene.getGeometryByID(parsedCylinder.id)) {
  40299. return null; // null since geometry could be something else than a cylinder...
  40300. }
  40301. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40302. if (BABYLON.Tags) {
  40303. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40304. }
  40305. scene.pushGeometry(cylinder, true);
  40306. return cylinder;
  40307. };
  40308. return CylinderGeometry;
  40309. }(_PrimitiveGeometry));
  40310. BABYLON.CylinderGeometry = CylinderGeometry;
  40311. /**
  40312. * Creates a new torus geometry
  40313. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40314. */
  40315. var TorusGeometry = /** @class */ (function (_super) {
  40316. __extends(TorusGeometry, _super);
  40317. /**
  40318. * Creates a new torus geometry
  40319. * @param id defines the unique ID of the geometry
  40320. * @param scene defines the hosting scene
  40321. * @param diameter defines the diameter of the torus
  40322. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40323. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40324. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40325. * @param mesh defines the hosting mesh (can be null)
  40326. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40327. */
  40328. function TorusGeometry(id, scene,
  40329. /**
  40330. * Defines the diameter of the torus
  40331. */
  40332. diameter,
  40333. /**
  40334. * Defines the thickness of the torus (ie. internal diameter)
  40335. */
  40336. thickness,
  40337. /**
  40338. * Defines the tesselation factor to apply to the torus
  40339. */
  40340. tessellation, canBeRegenerated, mesh,
  40341. /**
  40342. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40343. */
  40344. side) {
  40345. if (mesh === void 0) { mesh = null; }
  40346. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40347. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40348. _this.diameter = diameter;
  40349. _this.thickness = thickness;
  40350. _this.tessellation = tessellation;
  40351. _this.side = side;
  40352. return _this;
  40353. }
  40354. TorusGeometry.prototype._regenerateVertexData = function () {
  40355. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40356. };
  40357. TorusGeometry.prototype.copy = function (id) {
  40358. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40359. };
  40360. TorusGeometry.prototype.serialize = function () {
  40361. var serializationObject = _super.prototype.serialize.call(this);
  40362. serializationObject.diameter = this.diameter;
  40363. serializationObject.thickness = this.thickness;
  40364. serializationObject.tessellation = this.tessellation;
  40365. return serializationObject;
  40366. };
  40367. TorusGeometry.Parse = function (parsedTorus, scene) {
  40368. if (scene.getGeometryByID(parsedTorus.id)) {
  40369. return null; // null since geometry could be something else than a torus...
  40370. }
  40371. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40372. if (BABYLON.Tags) {
  40373. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40374. }
  40375. scene.pushGeometry(torus, true);
  40376. return torus;
  40377. };
  40378. return TorusGeometry;
  40379. }(_PrimitiveGeometry));
  40380. BABYLON.TorusGeometry = TorusGeometry;
  40381. /**
  40382. * Creates a new ground geometry
  40383. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40384. */
  40385. var GroundGeometry = /** @class */ (function (_super) {
  40386. __extends(GroundGeometry, _super);
  40387. /**
  40388. * Creates a new ground geometry
  40389. * @param id defines the unique ID of the geometry
  40390. * @param scene defines the hosting scene
  40391. * @param width defines the width of the ground
  40392. * @param height defines the height of the ground
  40393. * @param subdivisions defines the subdivisions to apply to the ground
  40394. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40395. * @param mesh defines the hosting mesh (can be null)
  40396. */
  40397. function GroundGeometry(id, scene,
  40398. /**
  40399. * Defines the width of the ground
  40400. */
  40401. width,
  40402. /**
  40403. * Defines the height of the ground
  40404. */
  40405. height,
  40406. /**
  40407. * Defines the subdivisions to apply to the ground
  40408. */
  40409. subdivisions, canBeRegenerated, mesh) {
  40410. if (mesh === void 0) { mesh = null; }
  40411. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40412. _this.width = width;
  40413. _this.height = height;
  40414. _this.subdivisions = subdivisions;
  40415. return _this;
  40416. }
  40417. GroundGeometry.prototype._regenerateVertexData = function () {
  40418. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40419. };
  40420. GroundGeometry.prototype.copy = function (id) {
  40421. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40422. };
  40423. GroundGeometry.prototype.serialize = function () {
  40424. var serializationObject = _super.prototype.serialize.call(this);
  40425. serializationObject.width = this.width;
  40426. serializationObject.height = this.height;
  40427. serializationObject.subdivisions = this.subdivisions;
  40428. return serializationObject;
  40429. };
  40430. GroundGeometry.Parse = function (parsedGround, scene) {
  40431. if (scene.getGeometryByID(parsedGround.id)) {
  40432. return null; // null since geometry could be something else than a ground...
  40433. }
  40434. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40435. if (BABYLON.Tags) {
  40436. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40437. }
  40438. scene.pushGeometry(ground, true);
  40439. return ground;
  40440. };
  40441. return GroundGeometry;
  40442. }(_PrimitiveGeometry));
  40443. BABYLON.GroundGeometry = GroundGeometry;
  40444. /**
  40445. * Creates a tiled ground geometry
  40446. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40447. */
  40448. var TiledGroundGeometry = /** @class */ (function (_super) {
  40449. __extends(TiledGroundGeometry, _super);
  40450. /**
  40451. * Creates a tiled ground geometry
  40452. * @param id defines the unique ID of the geometry
  40453. * @param scene defines the hosting scene
  40454. * @param xmin defines the minimum value on X axis
  40455. * @param zmin defines the minimum value on Z axis
  40456. * @param xmax defines the maximum value on X axis
  40457. * @param zmax defines the maximum value on Z axis
  40458. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40459. * @param precision defines the precision to use when computing the tiles
  40460. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40461. * @param mesh defines the hosting mesh (can be null)
  40462. */
  40463. function TiledGroundGeometry(id, scene,
  40464. /**
  40465. * Defines the minimum value on X axis
  40466. */
  40467. xmin,
  40468. /**
  40469. * Defines the minimum value on Z axis
  40470. */
  40471. zmin,
  40472. /**
  40473. * Defines the maximum value on X axis
  40474. */
  40475. xmax,
  40476. /**
  40477. * Defines the maximum value on Z axis
  40478. */
  40479. zmax,
  40480. /**
  40481. * Defines the subdivisions to apply to the ground
  40482. */
  40483. subdivisions,
  40484. /**
  40485. * Defines the precision to use when computing the tiles
  40486. */
  40487. precision, canBeRegenerated, mesh) {
  40488. if (mesh === void 0) { mesh = null; }
  40489. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40490. _this.xmin = xmin;
  40491. _this.zmin = zmin;
  40492. _this.xmax = xmax;
  40493. _this.zmax = zmax;
  40494. _this.subdivisions = subdivisions;
  40495. _this.precision = precision;
  40496. return _this;
  40497. }
  40498. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40499. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40500. };
  40501. TiledGroundGeometry.prototype.copy = function (id) {
  40502. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40503. };
  40504. return TiledGroundGeometry;
  40505. }(_PrimitiveGeometry));
  40506. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40507. /**
  40508. * Creates a plane geometry
  40509. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40510. */
  40511. var PlaneGeometry = /** @class */ (function (_super) {
  40512. __extends(PlaneGeometry, _super);
  40513. /**
  40514. * Creates a plane geometry
  40515. * @param id defines the unique ID of the geometry
  40516. * @param scene defines the hosting scene
  40517. * @param size defines the size of the plane (width === height)
  40518. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40519. * @param mesh defines the hosting mesh (can be null)
  40520. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40521. */
  40522. function PlaneGeometry(id, scene,
  40523. /**
  40524. * Defines the size of the plane (width === height)
  40525. */
  40526. size, canBeRegenerated, mesh,
  40527. /**
  40528. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40529. */
  40530. side) {
  40531. if (mesh === void 0) { mesh = null; }
  40532. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40533. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40534. _this.size = size;
  40535. _this.side = side;
  40536. return _this;
  40537. }
  40538. PlaneGeometry.prototype._regenerateVertexData = function () {
  40539. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40540. };
  40541. PlaneGeometry.prototype.copy = function (id) {
  40542. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40543. };
  40544. PlaneGeometry.prototype.serialize = function () {
  40545. var serializationObject = _super.prototype.serialize.call(this);
  40546. serializationObject.size = this.size;
  40547. return serializationObject;
  40548. };
  40549. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40550. if (scene.getGeometryByID(parsedPlane.id)) {
  40551. return null; // null since geometry could be something else than a ground...
  40552. }
  40553. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40554. if (BABYLON.Tags) {
  40555. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40556. }
  40557. scene.pushGeometry(plane, true);
  40558. return plane;
  40559. };
  40560. return PlaneGeometry;
  40561. }(_PrimitiveGeometry));
  40562. BABYLON.PlaneGeometry = PlaneGeometry;
  40563. /**
  40564. * Creates a torus knot geometry
  40565. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40566. */
  40567. var TorusKnotGeometry = /** @class */ (function (_super) {
  40568. __extends(TorusKnotGeometry, _super);
  40569. /**
  40570. * Creates a torus knot geometry
  40571. * @param id defines the unique ID of the geometry
  40572. * @param scene defines the hosting scene
  40573. * @param radius defines the radius of the torus knot
  40574. * @param tube defines the thickness of the torus knot tube
  40575. * @param radialSegments defines the number of radial segments
  40576. * @param tubularSegments defines the number of tubular segments
  40577. * @param p defines the first number of windings
  40578. * @param q defines the second number of windings
  40579. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40580. * @param mesh defines the hosting mesh (can be null)
  40581. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40582. */
  40583. function TorusKnotGeometry(id, scene,
  40584. /**
  40585. * Defines the radius of the torus knot
  40586. */
  40587. radius,
  40588. /**
  40589. * Defines the thickness of the torus knot tube
  40590. */
  40591. tube,
  40592. /**
  40593. * Defines the number of radial segments
  40594. */
  40595. radialSegments,
  40596. /**
  40597. * Defines the number of tubular segments
  40598. */
  40599. tubularSegments,
  40600. /**
  40601. * Defines the first number of windings
  40602. */
  40603. p,
  40604. /**
  40605. * Defines the second number of windings
  40606. */
  40607. q, canBeRegenerated, mesh,
  40608. /**
  40609. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40610. */
  40611. side) {
  40612. if (mesh === void 0) { mesh = null; }
  40613. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40614. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40615. _this.radius = radius;
  40616. _this.tube = tube;
  40617. _this.radialSegments = radialSegments;
  40618. _this.tubularSegments = tubularSegments;
  40619. _this.p = p;
  40620. _this.q = q;
  40621. _this.side = side;
  40622. return _this;
  40623. }
  40624. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40625. 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 });
  40626. };
  40627. TorusKnotGeometry.prototype.copy = function (id) {
  40628. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40629. };
  40630. TorusKnotGeometry.prototype.serialize = function () {
  40631. var serializationObject = _super.prototype.serialize.call(this);
  40632. serializationObject.radius = this.radius;
  40633. serializationObject.tube = this.tube;
  40634. serializationObject.radialSegments = this.radialSegments;
  40635. serializationObject.tubularSegments = this.tubularSegments;
  40636. serializationObject.p = this.p;
  40637. serializationObject.q = this.q;
  40638. return serializationObject;
  40639. };
  40640. ;
  40641. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40642. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40643. return null; // null since geometry could be something else than a ground...
  40644. }
  40645. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40646. if (BABYLON.Tags) {
  40647. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40648. }
  40649. scene.pushGeometry(torusKnot, true);
  40650. return torusKnot;
  40651. };
  40652. return TorusKnotGeometry;
  40653. }(_PrimitiveGeometry));
  40654. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40655. //}
  40656. })(BABYLON || (BABYLON = {}));
  40657. //# sourceMappingURL=babylon.geometry.js.map
  40658. var BABYLON;
  40659. (function (BABYLON) {
  40660. /**
  40661. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40662. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40663. */
  40664. var PostProcessManager = /** @class */ (function () {
  40665. /**
  40666. * Creates a new instance PostProcess
  40667. * @param scene The scene that the post process is associated with.
  40668. */
  40669. function PostProcessManager(scene) {
  40670. this._vertexBuffers = {};
  40671. this._scene = scene;
  40672. }
  40673. PostProcessManager.prototype._prepareBuffers = function () {
  40674. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40675. return;
  40676. }
  40677. // VBO
  40678. var vertices = [];
  40679. vertices.push(1, 1);
  40680. vertices.push(-1, 1);
  40681. vertices.push(-1, -1);
  40682. vertices.push(1, -1);
  40683. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40684. this._buildIndexBuffer();
  40685. };
  40686. PostProcessManager.prototype._buildIndexBuffer = function () {
  40687. // Indices
  40688. var indices = [];
  40689. indices.push(0);
  40690. indices.push(1);
  40691. indices.push(2);
  40692. indices.push(0);
  40693. indices.push(2);
  40694. indices.push(3);
  40695. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40696. };
  40697. /**
  40698. * Rebuilds the vertex buffers of the manager.
  40699. */
  40700. PostProcessManager.prototype._rebuild = function () {
  40701. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40702. if (!vb) {
  40703. return;
  40704. }
  40705. vb._rebuild();
  40706. this._buildIndexBuffer();
  40707. };
  40708. // Methods
  40709. /**
  40710. * Prepares a frame to be run through a post process.
  40711. * @param sourceTexture The input texture to the post procesess. (default: null)
  40712. * @param postProcesses An array of post processes to be run. (default: null)
  40713. * @returns True if the post processes were able to be run.
  40714. */
  40715. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40716. if (sourceTexture === void 0) { sourceTexture = null; }
  40717. if (postProcesses === void 0) { postProcesses = null; }
  40718. var camera = this._scene.activeCamera;
  40719. if (!camera) {
  40720. return false;
  40721. }
  40722. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40723. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40724. return false;
  40725. }
  40726. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40727. return true;
  40728. };
  40729. /**
  40730. * Manually render a set of post processes to a texture.
  40731. * @param postProcesses An array of post processes to be run.
  40732. * @param targetTexture The target texture to render to.
  40733. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40734. */
  40735. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40736. if (targetTexture === void 0) { targetTexture = null; }
  40737. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40738. var engine = this._scene.getEngine();
  40739. for (var index = 0; index < postProcesses.length; index++) {
  40740. if (index < postProcesses.length - 1) {
  40741. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40742. }
  40743. else {
  40744. if (targetTexture) {
  40745. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40746. }
  40747. else {
  40748. engine.restoreDefaultFramebuffer();
  40749. }
  40750. }
  40751. var pp = postProcesses[index];
  40752. var effect = pp.apply();
  40753. if (effect) {
  40754. pp.onBeforeRenderObservable.notifyObservers(effect);
  40755. // VBOs
  40756. this._prepareBuffers();
  40757. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40758. // Draw order
  40759. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40760. pp.onAfterRenderObservable.notifyObservers(effect);
  40761. }
  40762. }
  40763. // Restore depth buffer
  40764. engine.setDepthBuffer(true);
  40765. engine.setDepthWrite(true);
  40766. };
  40767. /**
  40768. * Finalize the result of the output of the postprocesses.
  40769. * @param doNotPresent If true the result will not be displayed to the screen.
  40770. * @param targetTexture The target texture to render to.
  40771. * @param faceIndex The index of the face to bind the target texture to.
  40772. * @param postProcesses The array of post processes to render.
  40773. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40774. */
  40775. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40776. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40777. var camera = this._scene.activeCamera;
  40778. if (!camera) {
  40779. return;
  40780. }
  40781. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40782. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40783. return;
  40784. }
  40785. var engine = this._scene.getEngine();
  40786. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40787. var pp = postProcesses[index];
  40788. if (index < len - 1) {
  40789. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40790. }
  40791. else {
  40792. if (targetTexture) {
  40793. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40794. pp._outputTexture = targetTexture;
  40795. }
  40796. else {
  40797. engine.restoreDefaultFramebuffer();
  40798. pp._outputTexture = null;
  40799. }
  40800. }
  40801. if (doNotPresent) {
  40802. break;
  40803. }
  40804. var effect = pp.apply();
  40805. if (effect) {
  40806. pp.onBeforeRenderObservable.notifyObservers(effect);
  40807. // VBOs
  40808. this._prepareBuffers();
  40809. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40810. // Draw order
  40811. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40812. pp.onAfterRenderObservable.notifyObservers(effect);
  40813. }
  40814. }
  40815. // Restore states
  40816. engine.setDepthBuffer(true);
  40817. engine.setDepthWrite(true);
  40818. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40819. };
  40820. /**
  40821. * Disposes of the post process manager.
  40822. */
  40823. PostProcessManager.prototype.dispose = function () {
  40824. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40825. if (buffer) {
  40826. buffer.dispose();
  40827. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40828. }
  40829. if (this._indexBuffer) {
  40830. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40831. this._indexBuffer = null;
  40832. }
  40833. };
  40834. return PostProcessManager;
  40835. }());
  40836. BABYLON.PostProcessManager = PostProcessManager;
  40837. })(BABYLON || (BABYLON = {}));
  40838. //# sourceMappingURL=babylon.postProcessManager.js.map
  40839. var BABYLON;
  40840. (function (BABYLON) {
  40841. /**
  40842. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40843. */
  40844. var PerformanceMonitor = /** @class */ (function () {
  40845. /**
  40846. * constructor
  40847. * @param frameSampleSize The number of samples required to saturate the sliding window
  40848. */
  40849. function PerformanceMonitor(frameSampleSize) {
  40850. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40851. this._enabled = true;
  40852. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40853. }
  40854. /**
  40855. * Samples current frame
  40856. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40857. */
  40858. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40859. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40860. if (!this._enabled)
  40861. return;
  40862. if (this._lastFrameTimeMs != null) {
  40863. var dt = timeMs - this._lastFrameTimeMs;
  40864. this._rollingFrameTime.add(dt);
  40865. }
  40866. this._lastFrameTimeMs = timeMs;
  40867. };
  40868. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40869. /**
  40870. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40871. * @return Average frame time in milliseconds
  40872. */
  40873. get: function () {
  40874. return this._rollingFrameTime.average;
  40875. },
  40876. enumerable: true,
  40877. configurable: true
  40878. });
  40879. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40880. /**
  40881. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40882. * @return Frame time variance in milliseconds squared
  40883. */
  40884. get: function () {
  40885. return this._rollingFrameTime.variance;
  40886. },
  40887. enumerable: true,
  40888. configurable: true
  40889. });
  40890. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40891. /**
  40892. * Returns the frame time of the most recent frame
  40893. * @return Frame time in milliseconds
  40894. */
  40895. get: function () {
  40896. return this._rollingFrameTime.history(0);
  40897. },
  40898. enumerable: true,
  40899. configurable: true
  40900. });
  40901. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40902. /**
  40903. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40904. * @return Framerate in frames per second
  40905. */
  40906. get: function () {
  40907. return 1000.0 / this._rollingFrameTime.average;
  40908. },
  40909. enumerable: true,
  40910. configurable: true
  40911. });
  40912. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40913. /**
  40914. * Returns the average framerate in frames per second using the most recent frame time
  40915. * @return Framerate in frames per second
  40916. */
  40917. get: function () {
  40918. var history = this._rollingFrameTime.history(0);
  40919. if (history === 0) {
  40920. return 0;
  40921. }
  40922. return 1000.0 / history;
  40923. },
  40924. enumerable: true,
  40925. configurable: true
  40926. });
  40927. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40928. /**
  40929. * Returns true if enough samples have been taken to completely fill the sliding window
  40930. * @return true if saturated
  40931. */
  40932. get: function () {
  40933. return this._rollingFrameTime.isSaturated();
  40934. },
  40935. enumerable: true,
  40936. configurable: true
  40937. });
  40938. /**
  40939. * Enables contributions to the sliding window sample set
  40940. */
  40941. PerformanceMonitor.prototype.enable = function () {
  40942. this._enabled = true;
  40943. };
  40944. /**
  40945. * Disables contributions to the sliding window sample set
  40946. * Samples will not be interpolated over the disabled period
  40947. */
  40948. PerformanceMonitor.prototype.disable = function () {
  40949. this._enabled = false;
  40950. //clear last sample to avoid interpolating over the disabled period when next enabled
  40951. this._lastFrameTimeMs = null;
  40952. };
  40953. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40954. /**
  40955. * Returns true if sampling is enabled
  40956. * @return true if enabled
  40957. */
  40958. get: function () {
  40959. return this._enabled;
  40960. },
  40961. enumerable: true,
  40962. configurable: true
  40963. });
  40964. /**
  40965. * Resets performance monitor
  40966. */
  40967. PerformanceMonitor.prototype.reset = function () {
  40968. //clear last sample to avoid interpolating over the disabled period when next enabled
  40969. this._lastFrameTimeMs = null;
  40970. //wipe record
  40971. this._rollingFrameTime.reset();
  40972. };
  40973. return PerformanceMonitor;
  40974. }());
  40975. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40976. /**
  40977. * RollingAverage
  40978. *
  40979. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40980. */
  40981. var RollingAverage = /** @class */ (function () {
  40982. /**
  40983. * constructor
  40984. * @param length The number of samples required to saturate the sliding window
  40985. */
  40986. function RollingAverage(length) {
  40987. this._samples = new Array(length);
  40988. this.reset();
  40989. }
  40990. /**
  40991. * Adds a sample to the sample set
  40992. * @param v The sample value
  40993. */
  40994. RollingAverage.prototype.add = function (v) {
  40995. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40996. var delta;
  40997. //we need to check if we've already wrapped round
  40998. if (this.isSaturated()) {
  40999. //remove bottom of stack from mean
  41000. var bottomValue = this._samples[this._pos];
  41001. delta = bottomValue - this.average;
  41002. this.average -= delta / (this._sampleCount - 1);
  41003. this._m2 -= delta * (bottomValue - this.average);
  41004. }
  41005. else {
  41006. this._sampleCount++;
  41007. }
  41008. //add new value to mean
  41009. delta = v - this.average;
  41010. this.average += delta / (this._sampleCount);
  41011. this._m2 += delta * (v - this.average);
  41012. //set the new variance
  41013. this.variance = this._m2 / (this._sampleCount - 1);
  41014. this._samples[this._pos] = v;
  41015. this._pos++;
  41016. this._pos %= this._samples.length; //positive wrap around
  41017. };
  41018. /**
  41019. * Returns previously added values or null if outside of history or outside the sliding window domain
  41020. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41021. * @return Value previously recorded with add() or null if outside of range
  41022. */
  41023. RollingAverage.prototype.history = function (i) {
  41024. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41025. return 0;
  41026. }
  41027. var i0 = this._wrapPosition(this._pos - 1.0);
  41028. return this._samples[this._wrapPosition(i0 - i)];
  41029. };
  41030. /**
  41031. * Returns true if enough samples have been taken to completely fill the sliding window
  41032. * @return true if sample-set saturated
  41033. */
  41034. RollingAverage.prototype.isSaturated = function () {
  41035. return this._sampleCount >= this._samples.length;
  41036. };
  41037. /**
  41038. * Resets the rolling average (equivalent to 0 samples taken so far)
  41039. */
  41040. RollingAverage.prototype.reset = function () {
  41041. this.average = 0;
  41042. this.variance = 0;
  41043. this._sampleCount = 0;
  41044. this._pos = 0;
  41045. this._m2 = 0;
  41046. };
  41047. /**
  41048. * Wraps a value around the sample range boundaries
  41049. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41050. * @return Wrapped position in sample range
  41051. */
  41052. RollingAverage.prototype._wrapPosition = function (i) {
  41053. var max = this._samples.length;
  41054. return ((i % max) + max) % max;
  41055. };
  41056. return RollingAverage;
  41057. }());
  41058. BABYLON.RollingAverage = RollingAverage;
  41059. })(BABYLON || (BABYLON = {}));
  41060. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41061. var BABYLON;
  41062. (function (BABYLON) {
  41063. /**
  41064. * This groups together the common properties used for image processing either in direct forward pass
  41065. * or through post processing effect depending on the use of the image processing pipeline in your scene
  41066. * or not.
  41067. */
  41068. var ImageProcessingConfiguration = /** @class */ (function () {
  41069. function ImageProcessingConfiguration() {
  41070. /**
  41071. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41072. */
  41073. this.colorCurves = new BABYLON.ColorCurves();
  41074. this._colorCurvesEnabled = false;
  41075. this._colorGradingEnabled = false;
  41076. this._colorGradingWithGreenDepth = true;
  41077. this._colorGradingBGR = true;
  41078. this._exposure = 1.0;
  41079. this._toneMappingEnabled = false;
  41080. this._contrast = 1.0;
  41081. /**
  41082. * Vignette stretch size.
  41083. */
  41084. this.vignetteStretch = 0;
  41085. /**
  41086. * Vignette centre X Offset.
  41087. */
  41088. this.vignetteCentreX = 0;
  41089. /**
  41090. * Vignette centre Y Offset.
  41091. */
  41092. this.vignetteCentreY = 0;
  41093. /**
  41094. * Vignette weight or intensity of the vignette effect.
  41095. */
  41096. this.vignetteWeight = 1.5;
  41097. /**
  41098. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41099. * if vignetteEnabled is set to true.
  41100. */
  41101. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41102. /**
  41103. * Camera field of view used by the Vignette effect.
  41104. */
  41105. this.vignetteCameraFov = 0.5;
  41106. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41107. this._vignetteEnabled = false;
  41108. this._applyByPostProcess = false;
  41109. this._isEnabled = true;
  41110. /**
  41111. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41112. */
  41113. this.onUpdateParameters = new BABYLON.Observable();
  41114. }
  41115. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41116. /**
  41117. * Gets wether the color curves effect is enabled.
  41118. */
  41119. get: function () {
  41120. return this._colorCurvesEnabled;
  41121. },
  41122. /**
  41123. * Sets wether the color curves effect is enabled.
  41124. */
  41125. set: function (value) {
  41126. if (this._colorCurvesEnabled === value) {
  41127. return;
  41128. }
  41129. this._colorCurvesEnabled = value;
  41130. this._updateParameters();
  41131. },
  41132. enumerable: true,
  41133. configurable: true
  41134. });
  41135. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41136. /**
  41137. * Gets wether the color grading effect is enabled.
  41138. */
  41139. get: function () {
  41140. return this._colorGradingEnabled;
  41141. },
  41142. /**
  41143. * Sets wether the color grading effect is enabled.
  41144. */
  41145. set: function (value) {
  41146. if (this._colorGradingEnabled === value) {
  41147. return;
  41148. }
  41149. this._colorGradingEnabled = value;
  41150. this._updateParameters();
  41151. },
  41152. enumerable: true,
  41153. configurable: true
  41154. });
  41155. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41156. /**
  41157. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41158. */
  41159. get: function () {
  41160. return this._colorGradingWithGreenDepth;
  41161. },
  41162. /**
  41163. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41164. */
  41165. set: function (value) {
  41166. if (this._colorGradingWithGreenDepth === value) {
  41167. return;
  41168. }
  41169. this._colorGradingWithGreenDepth = value;
  41170. this._updateParameters();
  41171. },
  41172. enumerable: true,
  41173. configurable: true
  41174. });
  41175. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41176. /**
  41177. * Gets wether the color grading texture contains BGR values.
  41178. */
  41179. get: function () {
  41180. return this._colorGradingBGR;
  41181. },
  41182. /**
  41183. * Sets wether the color grading texture contains BGR values.
  41184. */
  41185. set: function (value) {
  41186. if (this._colorGradingBGR === value) {
  41187. return;
  41188. }
  41189. this._colorGradingBGR = value;
  41190. this._updateParameters();
  41191. },
  41192. enumerable: true,
  41193. configurable: true
  41194. });
  41195. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41196. /**
  41197. * Gets the Exposure used in the effect.
  41198. */
  41199. get: function () {
  41200. return this._exposure;
  41201. },
  41202. /**
  41203. * Sets the Exposure used in the effect.
  41204. */
  41205. set: function (value) {
  41206. if (this._exposure === value) {
  41207. return;
  41208. }
  41209. this._exposure = value;
  41210. this._updateParameters();
  41211. },
  41212. enumerable: true,
  41213. configurable: true
  41214. });
  41215. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41216. /**
  41217. * Gets wether the tone mapping effect is enabled.
  41218. */
  41219. get: function () {
  41220. return this._toneMappingEnabled;
  41221. },
  41222. /**
  41223. * Sets wether the tone mapping effect is enabled.
  41224. */
  41225. set: function (value) {
  41226. if (this._toneMappingEnabled === value) {
  41227. return;
  41228. }
  41229. this._toneMappingEnabled = value;
  41230. this._updateParameters();
  41231. },
  41232. enumerable: true,
  41233. configurable: true
  41234. });
  41235. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41236. /**
  41237. * Gets the contrast used in the effect.
  41238. */
  41239. get: function () {
  41240. return this._contrast;
  41241. },
  41242. /**
  41243. * Sets the contrast used in the effect.
  41244. */
  41245. set: function (value) {
  41246. if (this._contrast === value) {
  41247. return;
  41248. }
  41249. this._contrast = value;
  41250. this._updateParameters();
  41251. },
  41252. enumerable: true,
  41253. configurable: true
  41254. });
  41255. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41256. /**
  41257. * Gets the vignette blend mode allowing different kind of effect.
  41258. */
  41259. get: function () {
  41260. return this._vignetteBlendMode;
  41261. },
  41262. /**
  41263. * Sets the vignette blend mode allowing different kind of effect.
  41264. */
  41265. set: function (value) {
  41266. if (this._vignetteBlendMode === value) {
  41267. return;
  41268. }
  41269. this._vignetteBlendMode = value;
  41270. this._updateParameters();
  41271. },
  41272. enumerable: true,
  41273. configurable: true
  41274. });
  41275. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41276. /**
  41277. * Gets wether the vignette effect is enabled.
  41278. */
  41279. get: function () {
  41280. return this._vignetteEnabled;
  41281. },
  41282. /**
  41283. * Sets wether the vignette effect is enabled.
  41284. */
  41285. set: function (value) {
  41286. if (this._vignetteEnabled === value) {
  41287. return;
  41288. }
  41289. this._vignetteEnabled = value;
  41290. this._updateParameters();
  41291. },
  41292. enumerable: true,
  41293. configurable: true
  41294. });
  41295. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41296. /**
  41297. * Gets wether the image processing is applied through a post process or not.
  41298. */
  41299. get: function () {
  41300. return this._applyByPostProcess;
  41301. },
  41302. /**
  41303. * Sets wether the image processing is applied through a post process or not.
  41304. */
  41305. set: function (value) {
  41306. if (this._applyByPostProcess === value) {
  41307. return;
  41308. }
  41309. this._applyByPostProcess = value;
  41310. this._updateParameters();
  41311. },
  41312. enumerable: true,
  41313. configurable: true
  41314. });
  41315. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41316. /**
  41317. * Gets wether the image processing is enabled or not.
  41318. */
  41319. get: function () {
  41320. return this._isEnabled;
  41321. },
  41322. /**
  41323. * Sets wether the image processing is enabled or not.
  41324. */
  41325. set: function (value) {
  41326. if (this._isEnabled === value) {
  41327. return;
  41328. }
  41329. this._isEnabled = value;
  41330. this._updateParameters();
  41331. },
  41332. enumerable: true,
  41333. configurable: true
  41334. });
  41335. /**
  41336. * Method called each time the image processing information changes requires to recompile the effect.
  41337. */
  41338. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41339. this.onUpdateParameters.notifyObservers(this);
  41340. };
  41341. ImageProcessingConfiguration.prototype.getClassName = function () {
  41342. return "ImageProcessingConfiguration";
  41343. };
  41344. /**
  41345. * Prepare the list of uniforms associated with the Image Processing effects.
  41346. * @param uniformsList The list of uniforms used in the effect
  41347. * @param defines the list of defines currently in use
  41348. */
  41349. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41350. if (defines.EXPOSURE) {
  41351. uniforms.push("exposureLinear");
  41352. }
  41353. if (defines.CONTRAST) {
  41354. uniforms.push("contrast");
  41355. }
  41356. if (defines.COLORGRADING) {
  41357. uniforms.push("colorTransformSettings");
  41358. }
  41359. if (defines.VIGNETTE) {
  41360. uniforms.push("vInverseScreenSize");
  41361. uniforms.push("vignetteSettings1");
  41362. uniforms.push("vignetteSettings2");
  41363. }
  41364. if (defines.COLORCURVES) {
  41365. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41366. }
  41367. };
  41368. /**
  41369. * Prepare the list of samplers associated with the Image Processing effects.
  41370. * @param uniformsList The list of uniforms used in the effect
  41371. * @param defines the list of defines currently in use
  41372. */
  41373. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41374. if (defines.COLORGRADING) {
  41375. samplersList.push("txColorTransform");
  41376. }
  41377. };
  41378. /**
  41379. * Prepare the list of defines associated to the shader.
  41380. * @param defines the list of defines to complete
  41381. */
  41382. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41383. if (forPostProcess === void 0) { forPostProcess = false; }
  41384. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41385. defines.VIGNETTE = false;
  41386. defines.TONEMAPPING = false;
  41387. defines.CONTRAST = false;
  41388. defines.EXPOSURE = false;
  41389. defines.COLORCURVES = false;
  41390. defines.COLORGRADING = false;
  41391. defines.COLORGRADING3D = false;
  41392. defines.IMAGEPROCESSING = false;
  41393. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41394. return;
  41395. }
  41396. defines.VIGNETTE = this.vignetteEnabled;
  41397. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41398. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41399. defines.TONEMAPPING = this.toneMappingEnabled;
  41400. defines.CONTRAST = (this.contrast !== 1.0);
  41401. defines.EXPOSURE = (this.exposure !== 1.0);
  41402. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41403. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41404. if (defines.COLORGRADING) {
  41405. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41406. }
  41407. else {
  41408. defines.COLORGRADING3D = false;
  41409. }
  41410. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41411. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41412. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41413. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41414. };
  41415. /**
  41416. * Returns true if all the image processing information are ready.
  41417. */
  41418. ImageProcessingConfiguration.prototype.isReady = function () {
  41419. // Color Grading texure can not be none blocking.
  41420. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41421. };
  41422. /**
  41423. * Binds the image processing to the shader.
  41424. * @param effect The effect to bind to
  41425. */
  41426. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41427. if (aspectRatio === void 0) { aspectRatio = 1; }
  41428. // Color Curves
  41429. if (this._colorCurvesEnabled && this.colorCurves) {
  41430. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41431. }
  41432. // Vignette
  41433. if (this._vignetteEnabled) {
  41434. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41435. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41436. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41437. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41438. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41439. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41440. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41441. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41442. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41443. var vignettePower = -2.0 * this.vignetteWeight;
  41444. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41445. }
  41446. // Exposure
  41447. effect.setFloat("exposureLinear", this.exposure);
  41448. // Contrast
  41449. effect.setFloat("contrast", this.contrast);
  41450. // Color transform settings
  41451. if (this.colorGradingTexture) {
  41452. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41453. var textureSize = this.colorGradingTexture.getSize().height;
  41454. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41455. 0.5 / textureSize, // textureOffset
  41456. textureSize, // textureSize
  41457. this.colorGradingTexture.level // weight
  41458. );
  41459. }
  41460. };
  41461. /**
  41462. * Clones the current image processing instance.
  41463. * @return The cloned image processing
  41464. */
  41465. ImageProcessingConfiguration.prototype.clone = function () {
  41466. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41467. };
  41468. /**
  41469. * Serializes the current image processing instance to a json representation.
  41470. * @return a JSON representation
  41471. */
  41472. ImageProcessingConfiguration.prototype.serialize = function () {
  41473. return BABYLON.SerializationHelper.Serialize(this);
  41474. };
  41475. /**
  41476. * Parses the image processing from a json representation.
  41477. * @param source the JSON source to parse
  41478. * @return The parsed image processing
  41479. */
  41480. ImageProcessingConfiguration.Parse = function (source) {
  41481. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41482. };
  41483. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41484. /**
  41485. * Used to apply the vignette as a mix with the pixel color.
  41486. */
  41487. get: function () {
  41488. return this._VIGNETTEMODE_MULTIPLY;
  41489. },
  41490. enumerable: true,
  41491. configurable: true
  41492. });
  41493. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41494. /**
  41495. * Used to apply the vignette as a replacement of the pixel color.
  41496. */
  41497. get: function () {
  41498. return this._VIGNETTEMODE_OPAQUE;
  41499. },
  41500. enumerable: true,
  41501. configurable: true
  41502. });
  41503. // Static constants associated to the image processing.
  41504. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41505. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41506. __decorate([
  41507. BABYLON.serializeAsColorCurves()
  41508. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41509. __decorate([
  41510. BABYLON.serialize()
  41511. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41512. __decorate([
  41513. BABYLON.serializeAsTexture()
  41514. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41515. __decorate([
  41516. BABYLON.serialize()
  41517. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41518. __decorate([
  41519. BABYLON.serialize()
  41520. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41521. __decorate([
  41522. BABYLON.serialize()
  41523. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41524. __decorate([
  41525. BABYLON.serialize()
  41526. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41527. __decorate([
  41528. BABYLON.serialize()
  41529. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41530. __decorate([
  41531. BABYLON.serialize()
  41532. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41533. __decorate([
  41534. BABYLON.serialize()
  41535. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41536. __decorate([
  41537. BABYLON.serialize()
  41538. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41539. __decorate([
  41540. BABYLON.serialize()
  41541. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41542. __decorate([
  41543. BABYLON.serialize()
  41544. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41545. __decorate([
  41546. BABYLON.serializeAsColor4()
  41547. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41548. __decorate([
  41549. BABYLON.serialize()
  41550. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41551. __decorate([
  41552. BABYLON.serialize()
  41553. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41554. __decorate([
  41555. BABYLON.serialize()
  41556. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41557. __decorate([
  41558. BABYLON.serialize()
  41559. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41560. __decorate([
  41561. BABYLON.serialize()
  41562. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41563. return ImageProcessingConfiguration;
  41564. }());
  41565. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41566. })(BABYLON || (BABYLON = {}));
  41567. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41568. var BABYLON;
  41569. (function (BABYLON) {
  41570. /**
  41571. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41572. * It can help converting any input color in a desired output one. This can then be used to create effects
  41573. * from sepia, black and white to sixties or futuristic rendering...
  41574. *
  41575. * The only supported format is currently 3dl.
  41576. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41577. */
  41578. var ColorGradingTexture = /** @class */ (function (_super) {
  41579. __extends(ColorGradingTexture, _super);
  41580. /**
  41581. * Instantiates a ColorGradingTexture from the following parameters.
  41582. *
  41583. * @param url The location of the color gradind data (currently only supporting 3dl)
  41584. * @param scene The scene the texture will be used in
  41585. */
  41586. function ColorGradingTexture(url, scene) {
  41587. var _this = _super.call(this, scene) || this;
  41588. if (!url) {
  41589. return _this;
  41590. }
  41591. _this._engine = scene.getEngine();
  41592. _this._textureMatrix = BABYLON.Matrix.Identity();
  41593. _this.name = url;
  41594. _this.url = url;
  41595. _this.hasAlpha = false;
  41596. _this.isCube = false;
  41597. _this.is3D = _this._engine.webGLVersion > 1;
  41598. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41599. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41600. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41601. _this.anisotropicFilteringLevel = 1;
  41602. _this._texture = _this._getFromCache(url, true);
  41603. if (!_this._texture) {
  41604. if (!scene.useDelayedTextureLoading) {
  41605. _this.loadTexture();
  41606. }
  41607. else {
  41608. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41609. }
  41610. }
  41611. return _this;
  41612. }
  41613. /**
  41614. * Returns the texture matrix used in most of the material.
  41615. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41616. */
  41617. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41618. return this._textureMatrix;
  41619. };
  41620. /**
  41621. * Occurs when the file being loaded is a .3dl LUT file.
  41622. */
  41623. ColorGradingTexture.prototype.load3dlTexture = function () {
  41624. var engine = this._engine;
  41625. var texture;
  41626. if (engine.webGLVersion === 1) {
  41627. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41628. }
  41629. else {
  41630. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41631. }
  41632. this._texture = texture;
  41633. var callback = function (text) {
  41634. if (typeof text !== "string") {
  41635. return;
  41636. }
  41637. var data = null;
  41638. var tempData = null;
  41639. var line;
  41640. var lines = text.split('\n');
  41641. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41642. var maxColor = 0;
  41643. for (var i = 0; i < lines.length; i++) {
  41644. line = lines[i];
  41645. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41646. continue;
  41647. if (line.indexOf('#') === 0)
  41648. continue;
  41649. var words = line.split(" ");
  41650. if (size === 0) {
  41651. // Number of space + one
  41652. size = words.length;
  41653. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41654. tempData = new Float32Array(size * size * size * 4);
  41655. continue;
  41656. }
  41657. if (size != 0) {
  41658. var r = Math.max(parseInt(words[0]), 0);
  41659. var g = Math.max(parseInt(words[1]), 0);
  41660. var b = Math.max(parseInt(words[2]), 0);
  41661. maxColor = Math.max(r, maxColor);
  41662. maxColor = Math.max(g, maxColor);
  41663. maxColor = Math.max(b, maxColor);
  41664. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41665. if (tempData) {
  41666. tempData[pixelStorageIndex + 0] = r;
  41667. tempData[pixelStorageIndex + 1] = g;
  41668. tempData[pixelStorageIndex + 2] = b;
  41669. }
  41670. pixelIndexSlice++;
  41671. if (pixelIndexSlice % size == 0) {
  41672. pixelIndexH++;
  41673. pixelIndexSlice = 0;
  41674. if (pixelIndexH % size == 0) {
  41675. pixelIndexW++;
  41676. pixelIndexH = 0;
  41677. }
  41678. }
  41679. }
  41680. }
  41681. if (tempData && data) {
  41682. for (var i = 0; i < tempData.length; i++) {
  41683. if (i > 0 && (i + 1) % 4 === 0) {
  41684. data[i] = 255;
  41685. }
  41686. else {
  41687. var value = tempData[i];
  41688. data[i] = (value / maxColor * 255);
  41689. }
  41690. }
  41691. }
  41692. if (texture.is3D) {
  41693. texture.updateSize(size, size, size);
  41694. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41695. }
  41696. else {
  41697. texture.updateSize(size * size, size);
  41698. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41699. }
  41700. };
  41701. var scene = this.getScene();
  41702. if (scene) {
  41703. scene._loadFile(this.url, callback);
  41704. }
  41705. else {
  41706. this._engine._loadFile(this.url, callback);
  41707. }
  41708. return this._texture;
  41709. };
  41710. /**
  41711. * Starts the loading process of the texture.
  41712. */
  41713. ColorGradingTexture.prototype.loadTexture = function () {
  41714. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41715. this.load3dlTexture();
  41716. }
  41717. };
  41718. /**
  41719. * Clones the color gradind texture.
  41720. */
  41721. ColorGradingTexture.prototype.clone = function () {
  41722. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41723. // Base texture
  41724. newTexture.level = this.level;
  41725. return newTexture;
  41726. };
  41727. /**
  41728. * Called during delayed load for textures.
  41729. */
  41730. ColorGradingTexture.prototype.delayLoad = function () {
  41731. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41732. return;
  41733. }
  41734. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41735. this._texture = this._getFromCache(this.url, true);
  41736. if (!this._texture) {
  41737. this.loadTexture();
  41738. }
  41739. };
  41740. /**
  41741. * Parses a color grading texture serialized by Babylon.
  41742. * @param parsedTexture The texture information being parsedTexture
  41743. * @param scene The scene to load the texture in
  41744. * @param rootUrl The root url of the data assets to load
  41745. * @return A color gradind texture
  41746. */
  41747. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41748. var texture = null;
  41749. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41750. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41751. texture.name = parsedTexture.name;
  41752. texture.level = parsedTexture.level;
  41753. }
  41754. return texture;
  41755. };
  41756. /**
  41757. * Serializes the LUT texture to json format.
  41758. */
  41759. ColorGradingTexture.prototype.serialize = function () {
  41760. if (!this.name) {
  41761. return null;
  41762. }
  41763. var serializationObject = {};
  41764. serializationObject.name = this.name;
  41765. serializationObject.level = this.level;
  41766. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41767. return serializationObject;
  41768. };
  41769. /**
  41770. * Empty line regex stored for GC.
  41771. */
  41772. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41773. return ColorGradingTexture;
  41774. }(BABYLON.BaseTexture));
  41775. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41776. })(BABYLON || (BABYLON = {}));
  41777. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41778. var BABYLON;
  41779. (function (BABYLON) {
  41780. /**
  41781. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41782. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41783. * 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;
  41784. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41785. */
  41786. var ColorCurves = /** @class */ (function () {
  41787. function ColorCurves() {
  41788. this._dirty = true;
  41789. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41790. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41791. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41792. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41793. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41794. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41795. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41796. this._globalHue = 30;
  41797. this._globalDensity = 0;
  41798. this._globalSaturation = 0;
  41799. this._globalExposure = 0;
  41800. this._highlightsHue = 30;
  41801. this._highlightsDensity = 0;
  41802. this._highlightsSaturation = 0;
  41803. this._highlightsExposure = 0;
  41804. this._midtonesHue = 30;
  41805. this._midtonesDensity = 0;
  41806. this._midtonesSaturation = 0;
  41807. this._midtonesExposure = 0;
  41808. this._shadowsHue = 30;
  41809. this._shadowsDensity = 0;
  41810. this._shadowsSaturation = 0;
  41811. this._shadowsExposure = 0;
  41812. }
  41813. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41814. /**
  41815. * Gets the global Hue value.
  41816. * 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).
  41817. */
  41818. get: function () {
  41819. return this._globalHue;
  41820. },
  41821. /**
  41822. * Sets the global Hue value.
  41823. * 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).
  41824. */
  41825. set: function (value) {
  41826. this._globalHue = value;
  41827. this._dirty = true;
  41828. },
  41829. enumerable: true,
  41830. configurable: true
  41831. });
  41832. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41833. /**
  41834. * Gets the global Density value.
  41835. * 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.
  41836. * Values less than zero provide a filter of opposite hue.
  41837. */
  41838. get: function () {
  41839. return this._globalDensity;
  41840. },
  41841. /**
  41842. * Sets the global Density value.
  41843. * 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.
  41844. * Values less than zero provide a filter of opposite hue.
  41845. */
  41846. set: function (value) {
  41847. this._globalDensity = value;
  41848. this._dirty = true;
  41849. },
  41850. enumerable: true,
  41851. configurable: true
  41852. });
  41853. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41854. /**
  41855. * Gets the global Saturation value.
  41856. * 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.
  41857. */
  41858. get: function () {
  41859. return this._globalSaturation;
  41860. },
  41861. /**
  41862. * Sets the global Saturation value.
  41863. * 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.
  41864. */
  41865. set: function (value) {
  41866. this._globalSaturation = value;
  41867. this._dirty = true;
  41868. },
  41869. enumerable: true,
  41870. configurable: true
  41871. });
  41872. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  41873. /**
  41874. * Gets the global Exposure value.
  41875. * 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.
  41876. */
  41877. get: function () {
  41878. return this._globalExposure;
  41879. },
  41880. /**
  41881. * Sets the global Exposure value.
  41882. * 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.
  41883. */
  41884. set: function (value) {
  41885. this._globalExposure = value;
  41886. this._dirty = true;
  41887. },
  41888. enumerable: true,
  41889. configurable: true
  41890. });
  41891. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41892. /**
  41893. * Gets the highlights Hue value.
  41894. * 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).
  41895. */
  41896. get: function () {
  41897. return this._highlightsHue;
  41898. },
  41899. /**
  41900. * Sets the highlights Hue value.
  41901. * 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).
  41902. */
  41903. set: function (value) {
  41904. this._highlightsHue = value;
  41905. this._dirty = true;
  41906. },
  41907. enumerable: true,
  41908. configurable: true
  41909. });
  41910. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41911. /**
  41912. * Gets the highlights Density value.
  41913. * 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.
  41914. * Values less than zero provide a filter of opposite hue.
  41915. */
  41916. get: function () {
  41917. return this._highlightsDensity;
  41918. },
  41919. /**
  41920. * Sets the highlights Density value.
  41921. * 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.
  41922. * Values less than zero provide a filter of opposite hue.
  41923. */
  41924. set: function (value) {
  41925. this._highlightsDensity = value;
  41926. this._dirty = true;
  41927. },
  41928. enumerable: true,
  41929. configurable: true
  41930. });
  41931. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41932. /**
  41933. * Gets the highlights Saturation value.
  41934. * 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.
  41935. */
  41936. get: function () {
  41937. return this._highlightsSaturation;
  41938. },
  41939. /**
  41940. * Sets the highlights Saturation value.
  41941. * 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.
  41942. */
  41943. set: function (value) {
  41944. this._highlightsSaturation = value;
  41945. this._dirty = true;
  41946. },
  41947. enumerable: true,
  41948. configurable: true
  41949. });
  41950. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41951. /**
  41952. * Gets the highlights Exposure value.
  41953. * 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.
  41954. */
  41955. get: function () {
  41956. return this._highlightsExposure;
  41957. },
  41958. /**
  41959. * Sets the highlights Exposure value.
  41960. * 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.
  41961. */
  41962. set: function (value) {
  41963. this._highlightsExposure = value;
  41964. this._dirty = true;
  41965. },
  41966. enumerable: true,
  41967. configurable: true
  41968. });
  41969. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41970. /**
  41971. * Gets the midtones Hue value.
  41972. * 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).
  41973. */
  41974. get: function () {
  41975. return this._midtonesHue;
  41976. },
  41977. /**
  41978. * Sets the midtones Hue value.
  41979. * 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).
  41980. */
  41981. set: function (value) {
  41982. this._midtonesHue = value;
  41983. this._dirty = true;
  41984. },
  41985. enumerable: true,
  41986. configurable: true
  41987. });
  41988. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41989. /**
  41990. * Gets the midtones Density value.
  41991. * 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.
  41992. * Values less than zero provide a filter of opposite hue.
  41993. */
  41994. get: function () {
  41995. return this._midtonesDensity;
  41996. },
  41997. /**
  41998. * Sets the midtones Density value.
  41999. * 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.
  42000. * Values less than zero provide a filter of opposite hue.
  42001. */
  42002. set: function (value) {
  42003. this._midtonesDensity = value;
  42004. this._dirty = true;
  42005. },
  42006. enumerable: true,
  42007. configurable: true
  42008. });
  42009. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  42010. /**
  42011. * Gets the midtones Saturation value.
  42012. * 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.
  42013. */
  42014. get: function () {
  42015. return this._midtonesSaturation;
  42016. },
  42017. /**
  42018. * Sets the midtones Saturation value.
  42019. * 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.
  42020. */
  42021. set: function (value) {
  42022. this._midtonesSaturation = value;
  42023. this._dirty = true;
  42024. },
  42025. enumerable: true,
  42026. configurable: true
  42027. });
  42028. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  42029. /**
  42030. * Gets the midtones Exposure value.
  42031. * 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.
  42032. */
  42033. get: function () {
  42034. return this._midtonesExposure;
  42035. },
  42036. /**
  42037. * Sets the midtones Exposure value.
  42038. * 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.
  42039. */
  42040. set: function (value) {
  42041. this._midtonesExposure = value;
  42042. this._dirty = true;
  42043. },
  42044. enumerable: true,
  42045. configurable: true
  42046. });
  42047. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42048. /**
  42049. * Gets the shadows Hue value.
  42050. * 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).
  42051. */
  42052. get: function () {
  42053. return this._shadowsHue;
  42054. },
  42055. /**
  42056. * Sets the shadows Hue value.
  42057. * 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).
  42058. */
  42059. set: function (value) {
  42060. this._shadowsHue = value;
  42061. this._dirty = true;
  42062. },
  42063. enumerable: true,
  42064. configurable: true
  42065. });
  42066. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42067. /**
  42068. * Gets the shadows Density value.
  42069. * 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.
  42070. * Values less than zero provide a filter of opposite hue.
  42071. */
  42072. get: function () {
  42073. return this._shadowsDensity;
  42074. },
  42075. /**
  42076. * Sets the shadows Density value.
  42077. * 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.
  42078. * Values less than zero provide a filter of opposite hue.
  42079. */
  42080. set: function (value) {
  42081. this._shadowsDensity = value;
  42082. this._dirty = true;
  42083. },
  42084. enumerable: true,
  42085. configurable: true
  42086. });
  42087. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42088. /**
  42089. * Gets the shadows Saturation value.
  42090. * 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.
  42091. */
  42092. get: function () {
  42093. return this._shadowsSaturation;
  42094. },
  42095. /**
  42096. * Sets the shadows Saturation value.
  42097. * 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.
  42098. */
  42099. set: function (value) {
  42100. this._shadowsSaturation = value;
  42101. this._dirty = true;
  42102. },
  42103. enumerable: true,
  42104. configurable: true
  42105. });
  42106. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42107. /**
  42108. * Gets the shadows Exposure value.
  42109. * 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.
  42110. */
  42111. get: function () {
  42112. return this._shadowsExposure;
  42113. },
  42114. /**
  42115. * Sets the shadows Exposure value.
  42116. * 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.
  42117. */
  42118. set: function (value) {
  42119. this._shadowsExposure = value;
  42120. this._dirty = true;
  42121. },
  42122. enumerable: true,
  42123. configurable: true
  42124. });
  42125. ColorCurves.prototype.getClassName = function () {
  42126. return "ColorCurves";
  42127. };
  42128. /**
  42129. * Binds the color curves to the shader.
  42130. * @param colorCurves The color curve to bind
  42131. * @param effect The effect to bind to
  42132. */
  42133. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42134. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42135. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42136. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42137. if (colorCurves._dirty) {
  42138. colorCurves._dirty = false;
  42139. // Fill in global info.
  42140. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42141. // Compute highlights info.
  42142. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42143. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42144. // Compute midtones info.
  42145. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42146. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42147. // Compute shadows info.
  42148. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42149. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42150. // Compute deltas (neutral is midtones).
  42151. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42152. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42153. }
  42154. if (effect) {
  42155. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42156. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42157. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42158. }
  42159. };
  42160. /**
  42161. * Prepare the list of uniforms associated with the ColorCurves effects.
  42162. * @param uniformsList The list of uniforms used in the effect
  42163. */
  42164. ColorCurves.PrepareUniforms = function (uniformsList) {
  42165. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42166. };
  42167. /**
  42168. * Returns color grading data based on a hue, density, saturation and exposure value.
  42169. * @param filterHue The hue of the color filter.
  42170. * @param filterDensity The density of the color filter.
  42171. * @param saturation The saturation.
  42172. * @param exposure The exposure.
  42173. * @param result The result data container.
  42174. */
  42175. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42176. if (hue == null) {
  42177. return;
  42178. }
  42179. hue = ColorCurves.clamp(hue, 0, 360);
  42180. density = ColorCurves.clamp(density, -100, 100);
  42181. saturation = ColorCurves.clamp(saturation, -100, 100);
  42182. exposure = ColorCurves.clamp(exposure, -100, 100);
  42183. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42184. // so that the maximum filter density is only 50% control. This provides fine control
  42185. // for small values and reasonable range.
  42186. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42187. density *= 0.5;
  42188. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42189. if (density < 0) {
  42190. density *= -1;
  42191. hue = (hue + 180) % 360;
  42192. }
  42193. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42194. result.scaleToRef(2, result);
  42195. result.a = 1 + 0.01 * saturation;
  42196. };
  42197. /**
  42198. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42199. * @param value The input slider value in range [-100,100].
  42200. * @returns Adjusted value.
  42201. */
  42202. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42203. value /= 100;
  42204. var x = Math.abs(value);
  42205. x = Math.pow(x, 2);
  42206. if (value < 0) {
  42207. x *= -1;
  42208. }
  42209. x *= 100;
  42210. return x;
  42211. };
  42212. /**
  42213. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42214. * @param hue The hue (H) input.
  42215. * @param saturation The saturation (S) input.
  42216. * @param brightness The brightness (B) input.
  42217. * @result An RGBA color represented as Vector4.
  42218. */
  42219. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42220. var h = ColorCurves.clamp(hue, 0, 360);
  42221. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42222. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42223. if (s === 0) {
  42224. result.r = v;
  42225. result.g = v;
  42226. result.b = v;
  42227. }
  42228. else {
  42229. // sector 0 to 5
  42230. h /= 60;
  42231. var i = Math.floor(h);
  42232. // fractional part of h
  42233. var f = h - i;
  42234. var p = v * (1 - s);
  42235. var q = v * (1 - s * f);
  42236. var t = v * (1 - s * (1 - f));
  42237. switch (i) {
  42238. case 0:
  42239. result.r = v;
  42240. result.g = t;
  42241. result.b = p;
  42242. break;
  42243. case 1:
  42244. result.r = q;
  42245. result.g = v;
  42246. result.b = p;
  42247. break;
  42248. case 2:
  42249. result.r = p;
  42250. result.g = v;
  42251. result.b = t;
  42252. break;
  42253. case 3:
  42254. result.r = p;
  42255. result.g = q;
  42256. result.b = v;
  42257. break;
  42258. case 4:
  42259. result.r = t;
  42260. result.g = p;
  42261. result.b = v;
  42262. break;
  42263. default: // case 5:
  42264. result.r = v;
  42265. result.g = p;
  42266. result.b = q;
  42267. break;
  42268. }
  42269. }
  42270. result.a = 1;
  42271. };
  42272. /**
  42273. * Returns a value clamped between min and max
  42274. * @param value The value to clamp
  42275. * @param min The minimum of value
  42276. * @param max The maximum of value
  42277. * @returns The clamped value.
  42278. */
  42279. ColorCurves.clamp = function (value, min, max) {
  42280. return Math.min(Math.max(value, min), max);
  42281. };
  42282. /**
  42283. * Clones the current color curve instance.
  42284. * @return The cloned curves
  42285. */
  42286. ColorCurves.prototype.clone = function () {
  42287. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42288. };
  42289. /**
  42290. * Serializes the current color curve instance to a json representation.
  42291. * @return a JSON representation
  42292. */
  42293. ColorCurves.prototype.serialize = function () {
  42294. return BABYLON.SerializationHelper.Serialize(this);
  42295. };
  42296. /**
  42297. * Parses the color curve from a json representation.
  42298. * @param source the JSON source to parse
  42299. * @return The parsed curves
  42300. */
  42301. ColorCurves.Parse = function (source) {
  42302. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42303. };
  42304. __decorate([
  42305. BABYLON.serialize()
  42306. ], ColorCurves.prototype, "_globalHue", void 0);
  42307. __decorate([
  42308. BABYLON.serialize()
  42309. ], ColorCurves.prototype, "_globalDensity", void 0);
  42310. __decorate([
  42311. BABYLON.serialize()
  42312. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42313. __decorate([
  42314. BABYLON.serialize()
  42315. ], ColorCurves.prototype, "_globalExposure", void 0);
  42316. __decorate([
  42317. BABYLON.serialize()
  42318. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42319. __decorate([
  42320. BABYLON.serialize()
  42321. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42322. __decorate([
  42323. BABYLON.serialize()
  42324. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42325. __decorate([
  42326. BABYLON.serialize()
  42327. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42328. __decorate([
  42329. BABYLON.serialize()
  42330. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42331. __decorate([
  42332. BABYLON.serialize()
  42333. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42334. __decorate([
  42335. BABYLON.serialize()
  42336. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42337. __decorate([
  42338. BABYLON.serialize()
  42339. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42340. return ColorCurves;
  42341. }());
  42342. BABYLON.ColorCurves = ColorCurves;
  42343. })(BABYLON || (BABYLON = {}));
  42344. //# sourceMappingURL=babylon.colorCurves.js.map
  42345. //# sourceMappingURL=babylon.behavior.js.map
  42346. var BABYLON;
  42347. (function (BABYLON) {
  42348. /**
  42349. * "Static Class" containing the most commonly used helper while dealing with material for
  42350. * rendering purpose.
  42351. *
  42352. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42353. *
  42354. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42355. */
  42356. var MaterialHelper = /** @class */ (function () {
  42357. function MaterialHelper() {
  42358. }
  42359. /**
  42360. * Bind the current view position to an effect.
  42361. * @param effect The effect to be bound
  42362. * @param scene The scene the eyes position is used from
  42363. */
  42364. MaterialHelper.BindEyePosition = function (effect, scene) {
  42365. if (scene._forcedViewPosition) {
  42366. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42367. return;
  42368. }
  42369. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42370. };
  42371. /**
  42372. * Helps preparing the defines values about the UVs in used in the effect.
  42373. * UVs are shared as much as we can accross chanels in the shaders.
  42374. * @param texture The texture we are preparing the UVs for
  42375. * @param defines The defines to update
  42376. * @param key The chanel key "diffuse", "specular"... used in the shader
  42377. */
  42378. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42379. defines._needUVs = true;
  42380. defines[key] = true;
  42381. if (texture.getTextureMatrix().isIdentity(true)) {
  42382. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42383. if (texture.coordinatesIndex === 0) {
  42384. defines["MAINUV1"] = true;
  42385. }
  42386. else {
  42387. defines["MAINUV2"] = true;
  42388. }
  42389. }
  42390. else {
  42391. defines[key + "DIRECTUV"] = 0;
  42392. }
  42393. };
  42394. /**
  42395. * Binds a texture matrix value to its corrsponding uniform
  42396. * @param texture The texture to bind the matrix for
  42397. * @param uniformBuffer The uniform buffer receivin the data
  42398. * @param key The chanel key "diffuse", "specular"... used in the shader
  42399. */
  42400. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42401. var matrix = texture.getTextureMatrix();
  42402. if (!matrix.isIdentity(true)) {
  42403. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42404. }
  42405. };
  42406. /**
  42407. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42408. * @param mesh defines the current mesh
  42409. * @param scene defines the current scene
  42410. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42411. * @param pointsCloud defines if point cloud rendering has to be turned on
  42412. * @param fogEnabled defines if fog has to be turned on
  42413. * @param alphaTest defines if alpha testing has to be turned on
  42414. * @param defines defines the current list of defines
  42415. */
  42416. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42417. if (defines._areMiscDirty) {
  42418. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42419. defines["POINTSIZE"] = pointsCloud;
  42420. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42421. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42422. defines["ALPHATEST"] = alphaTest;
  42423. }
  42424. };
  42425. /**
  42426. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42427. * @param scene defines the current scene
  42428. * @param engine defines the current engine
  42429. * @param defines specifies the list of active defines
  42430. * @param useInstances defines if instances have to be turned on
  42431. * @param useClipPlane defines if clip plane have to be turned on
  42432. */
  42433. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42434. if (useClipPlane === void 0) { useClipPlane = null; }
  42435. var changed = false;
  42436. if (useClipPlane == null) {
  42437. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42438. }
  42439. if (defines["CLIPPLANE"] !== useClipPlane) {
  42440. defines["CLIPPLANE"] = useClipPlane;
  42441. changed = true;
  42442. }
  42443. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42444. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42445. changed = true;
  42446. }
  42447. if (defines["INSTANCES"] !== useInstances) {
  42448. defines["INSTANCES"] = useInstances;
  42449. changed = true;
  42450. }
  42451. if (changed) {
  42452. defines.markAsUnprocessed();
  42453. }
  42454. };
  42455. /**
  42456. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42457. * @param mesh The mesh containing the geometry data we will draw
  42458. * @param defines The defines to update
  42459. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42460. * @param useBones Precise whether bones should be used or not (override mesh info)
  42461. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42462. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42463. * @returns false if defines are considered not dirty and have not been checked
  42464. */
  42465. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42466. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42467. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42468. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42469. return false;
  42470. }
  42471. defines._normals = defines._needNormals;
  42472. defines._uvs = defines._needUVs;
  42473. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42474. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42475. defines["TANGENT"] = true;
  42476. }
  42477. if (defines._needUVs) {
  42478. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42479. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42480. }
  42481. else {
  42482. defines["UV1"] = false;
  42483. defines["UV2"] = false;
  42484. }
  42485. if (useVertexColor) {
  42486. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42487. defines["VERTEXCOLOR"] = hasVertexColors;
  42488. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42489. }
  42490. if (useBones) {
  42491. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42492. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42493. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42494. }
  42495. else {
  42496. defines["NUM_BONE_INFLUENCERS"] = 0;
  42497. defines["BonesPerMesh"] = 0;
  42498. }
  42499. }
  42500. if (useMorphTargets) {
  42501. var manager = mesh.morphTargetManager;
  42502. if (manager) {
  42503. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42504. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42505. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42506. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42507. }
  42508. else {
  42509. defines["MORPHTARGETS_TANGENT"] = false;
  42510. defines["MORPHTARGETS_NORMAL"] = false;
  42511. defines["MORPHTARGETS"] = false;
  42512. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42513. }
  42514. }
  42515. return true;
  42516. };
  42517. /**
  42518. * Prepares the defines related to the light information passed in parameter
  42519. * @param scene The scene we are intending to draw
  42520. * @param mesh The mesh the effect is compiling for
  42521. * @param defines The defines to update
  42522. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42523. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42524. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42525. * @returns true if normals will be required for the rest of the effect
  42526. */
  42527. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42528. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42529. if (disableLighting === void 0) { disableLighting = false; }
  42530. if (!defines._areLightsDirty) {
  42531. return defines._needNormals;
  42532. }
  42533. var lightIndex = 0;
  42534. var needNormals = false;
  42535. var needRebuild = false;
  42536. var lightmapMode = false;
  42537. var shadowEnabled = false;
  42538. var specularEnabled = false;
  42539. if (scene.lightsEnabled && !disableLighting) {
  42540. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42541. var light = _a[_i];
  42542. needNormals = true;
  42543. if (defines["LIGHT" + lightIndex] === undefined) {
  42544. needRebuild = true;
  42545. }
  42546. defines["LIGHT" + lightIndex] = true;
  42547. defines["SPOTLIGHT" + lightIndex] = false;
  42548. defines["HEMILIGHT" + lightIndex] = false;
  42549. defines["POINTLIGHT" + lightIndex] = false;
  42550. defines["DIRLIGHT" + lightIndex] = false;
  42551. var type;
  42552. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42553. type = "SPOTLIGHT" + lightIndex;
  42554. var spotLight = light;
  42555. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42556. }
  42557. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42558. type = "HEMILIGHT" + lightIndex;
  42559. }
  42560. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42561. type = "POINTLIGHT" + lightIndex;
  42562. }
  42563. else {
  42564. type = "DIRLIGHT" + lightIndex;
  42565. }
  42566. defines[type] = true;
  42567. // Specular
  42568. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42569. specularEnabled = true;
  42570. }
  42571. // Shadows
  42572. defines["SHADOW" + lightIndex] = false;
  42573. defines["SHADOWPCF" + lightIndex] = false;
  42574. defines["SHADOWPCSS" + lightIndex] = false;
  42575. defines["SHADOWPOISSON" + lightIndex] = false;
  42576. defines["SHADOWESM" + lightIndex] = false;
  42577. defines["SHADOWCUBE" + lightIndex] = false;
  42578. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42579. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42580. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42581. var shadowGenerator = light.getShadowGenerator();
  42582. if (shadowGenerator) {
  42583. shadowEnabled = true;
  42584. shadowGenerator.prepareDefines(defines, lightIndex);
  42585. }
  42586. }
  42587. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42588. lightmapMode = true;
  42589. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42590. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42591. }
  42592. else {
  42593. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42594. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42595. }
  42596. lightIndex++;
  42597. if (lightIndex === maxSimultaneousLights)
  42598. break;
  42599. }
  42600. }
  42601. defines["SPECULARTERM"] = specularEnabled;
  42602. defines["SHADOWS"] = shadowEnabled;
  42603. // Resetting all other lights if any
  42604. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42605. if (defines["LIGHT" + index] !== undefined) {
  42606. defines["LIGHT" + index] = false;
  42607. defines["HEMILIGHT" + lightIndex] = false;
  42608. defines["POINTLIGHT" + lightIndex] = false;
  42609. defines["DIRLIGHT" + lightIndex] = false;
  42610. defines["SPOTLIGHT" + lightIndex] = false;
  42611. defines["SHADOW" + lightIndex] = false;
  42612. }
  42613. }
  42614. var caps = scene.getEngine().getCaps();
  42615. if (defines["SHADOWFLOAT"] === undefined) {
  42616. needRebuild = true;
  42617. }
  42618. defines["SHADOWFLOAT"] = shadowEnabled &&
  42619. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42620. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42621. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42622. if (needRebuild) {
  42623. defines.rebuild();
  42624. }
  42625. return needNormals;
  42626. };
  42627. /**
  42628. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42629. * that won t be acctive due to defines being turned off.
  42630. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42631. * @param samplersList The samplers list
  42632. * @param defines The defines helping in the list generation
  42633. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42634. */
  42635. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42636. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42637. var uniformsList;
  42638. var uniformBuffersList = null;
  42639. if (uniformsListOrOptions.uniformsNames) {
  42640. var options = uniformsListOrOptions;
  42641. uniformsList = options.uniformsNames;
  42642. uniformBuffersList = options.uniformBuffersNames;
  42643. samplersList = options.samplers;
  42644. defines = options.defines;
  42645. maxSimultaneousLights = options.maxSimultaneousLights;
  42646. }
  42647. else {
  42648. uniformsList = uniformsListOrOptions;
  42649. if (!samplersList) {
  42650. samplersList = [];
  42651. }
  42652. }
  42653. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42654. if (!defines["LIGHT" + lightIndex]) {
  42655. break;
  42656. }
  42657. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42658. if (uniformBuffersList) {
  42659. uniformBuffersList.push("Light" + lightIndex);
  42660. }
  42661. samplersList.push("shadowSampler" + lightIndex);
  42662. samplersList.push("depthSampler" + lightIndex);
  42663. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42664. samplersList.push("projectionLightSampler" + lightIndex);
  42665. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42666. }
  42667. }
  42668. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42669. uniformsList.push("morphTargetInfluences");
  42670. }
  42671. };
  42672. /**
  42673. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42674. * @param defines The defines to update while falling back
  42675. * @param fallbacks The authorized effect fallbacks
  42676. * @param maxSimultaneousLights The maximum number of lights allowed
  42677. * @param rank the current rank of the Effect
  42678. * @returns The newly affected rank
  42679. */
  42680. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42681. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42682. if (rank === void 0) { rank = 0; }
  42683. var lightFallbackRank = 0;
  42684. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42685. if (!defines["LIGHT" + lightIndex]) {
  42686. break;
  42687. }
  42688. if (lightIndex > 0) {
  42689. lightFallbackRank = rank + lightIndex;
  42690. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42691. }
  42692. if (!defines["SHADOWS"]) {
  42693. if (defines["SHADOW" + lightIndex]) {
  42694. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42695. }
  42696. if (defines["SHADOWPCF" + lightIndex]) {
  42697. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42698. }
  42699. if (defines["SHADOWPCSS" + lightIndex]) {
  42700. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42701. }
  42702. if (defines["SHADOWPOISSON" + lightIndex]) {
  42703. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42704. }
  42705. if (defines["SHADOWESM" + lightIndex]) {
  42706. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42707. }
  42708. }
  42709. }
  42710. return lightFallbackRank++;
  42711. };
  42712. /**
  42713. * Prepares the list of attributes required for morph targets according to the effect defines.
  42714. * @param attribs The current list of supported attribs
  42715. * @param mesh The mesh to prepare the morph targets attributes for
  42716. * @param defines The current Defines of the effect
  42717. */
  42718. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42719. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42720. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42721. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42722. var manager = mesh.morphTargetManager;
  42723. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42724. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42725. for (var index = 0; index < influencers; index++) {
  42726. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42727. if (normal) {
  42728. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42729. }
  42730. if (tangent) {
  42731. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42732. }
  42733. if (attribs.length > maxAttributesCount) {
  42734. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42735. }
  42736. }
  42737. }
  42738. };
  42739. /**
  42740. * Prepares the list of attributes required for bones according to the effect defines.
  42741. * @param attribs The current list of supported attribs
  42742. * @param mesh The mesh to prepare the bones attributes for
  42743. * @param defines The current Defines of the effect
  42744. * @param fallbacks The current efffect fallback strategy
  42745. */
  42746. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42747. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42748. fallbacks.addCPUSkinningFallback(0, mesh);
  42749. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42750. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42751. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42752. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42753. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42754. }
  42755. }
  42756. };
  42757. /**
  42758. * Prepares the list of attributes required for instances according to the effect defines.
  42759. * @param attribs The current list of supported attribs
  42760. * @param defines The current Defines of the effect
  42761. */
  42762. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42763. if (defines["INSTANCES"]) {
  42764. attribs.push("world0");
  42765. attribs.push("world1");
  42766. attribs.push("world2");
  42767. attribs.push("world3");
  42768. }
  42769. };
  42770. /**
  42771. * Binds the light shadow information to the effect for the given mesh.
  42772. * @param light The light containing the generator
  42773. * @param scene The scene the lights belongs to
  42774. * @param mesh The mesh we are binding the information to render
  42775. * @param lightIndex The light index in the effect used to render the mesh
  42776. * @param effect The effect we are binding the data to
  42777. */
  42778. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42779. if (light.shadowEnabled && mesh.receiveShadows) {
  42780. var shadowGenerator = light.getShadowGenerator();
  42781. if (shadowGenerator) {
  42782. shadowGenerator.bindShadowLight(lightIndex, effect);
  42783. }
  42784. }
  42785. };
  42786. /**
  42787. * Binds the light information to the effect.
  42788. * @param light The light containing the generator
  42789. * @param effect The effect we are binding the data to
  42790. * @param lightIndex The light index in the effect used to render
  42791. */
  42792. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42793. light.transferToEffect(effect, lightIndex + "");
  42794. };
  42795. /**
  42796. * Binds the lights information from the scene to the effect for the given mesh.
  42797. * @param scene The scene the lights belongs to
  42798. * @param mesh The mesh we are binding the information to render
  42799. * @param effect The effect we are binding the data to
  42800. * @param defines The generated defines for the effect
  42801. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42802. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42803. */
  42804. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42805. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42806. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42807. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42808. for (var i = 0; i < len; i++) {
  42809. var light = mesh._lightSources[i];
  42810. var iAsString = i.toString();
  42811. var scaledIntensity = light.getScaledIntensity();
  42812. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42813. MaterialHelper.BindLightProperties(light, effect, i);
  42814. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42815. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42816. if (defines["SPECULARTERM"]) {
  42817. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42818. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42819. }
  42820. // Shadows
  42821. if (scene.shadowsEnabled) {
  42822. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42823. }
  42824. light._uniformBuffer.update();
  42825. }
  42826. };
  42827. /**
  42828. * Binds the fog information from the scene to the effect for the given mesh.
  42829. * @param scene The scene the lights belongs to
  42830. * @param mesh The mesh we are binding the information to render
  42831. * @param effect The effect we are binding the data to
  42832. */
  42833. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42834. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42835. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42836. effect.setColor3("vFogColor", scene.fogColor);
  42837. }
  42838. };
  42839. /**
  42840. * Binds the bones information from the mesh to the effect.
  42841. * @param mesh The mesh we are binding the information to render
  42842. * @param effect The effect we are binding the data to
  42843. */
  42844. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42845. if (!effect || !mesh) {
  42846. return;
  42847. }
  42848. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42849. mesh.computeBonesUsingShaders = false;
  42850. }
  42851. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42852. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42853. if (matrices) {
  42854. effect.setMatrices("mBones", matrices);
  42855. }
  42856. }
  42857. };
  42858. /**
  42859. * Binds the morph targets information from the mesh to the effect.
  42860. * @param abstractMesh The mesh we are binding the information to render
  42861. * @param effect The effect we are binding the data to
  42862. */
  42863. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42864. var manager = abstractMesh.morphTargetManager;
  42865. if (!abstractMesh || !manager) {
  42866. return;
  42867. }
  42868. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42869. };
  42870. /**
  42871. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42872. * @param defines The generated defines used in the effect
  42873. * @param effect The effect we are binding the data to
  42874. * @param scene The scene we are willing to render with logarithmic scale for
  42875. */
  42876. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42877. if (defines["LOGARITHMICDEPTH"]) {
  42878. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42879. }
  42880. };
  42881. /**
  42882. * Binds the clip plane information from the scene to the effect.
  42883. * @param scene The scene the clip plane information are extracted from
  42884. * @param effect The effect we are binding the data to
  42885. */
  42886. MaterialHelper.BindClipPlane = function (effect, scene) {
  42887. if (scene.clipPlane) {
  42888. var clipPlane = scene.clipPlane;
  42889. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42890. }
  42891. };
  42892. return MaterialHelper;
  42893. }());
  42894. BABYLON.MaterialHelper = MaterialHelper;
  42895. })(BABYLON || (BABYLON = {}));
  42896. //# sourceMappingURL=babylon.materialHelper.js.map
  42897. var BABYLON;
  42898. (function (BABYLON) {
  42899. var PushMaterial = /** @class */ (function (_super) {
  42900. __extends(PushMaterial, _super);
  42901. function PushMaterial(name, scene) {
  42902. var _this = _super.call(this, name, scene) || this;
  42903. _this._normalMatrix = new BABYLON.Matrix();
  42904. _this.storeEffectOnSubMeshes = true;
  42905. return _this;
  42906. }
  42907. PushMaterial.prototype.getEffect = function () {
  42908. return this._activeEffect;
  42909. };
  42910. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42911. if (!mesh) {
  42912. return false;
  42913. }
  42914. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42915. return true;
  42916. }
  42917. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42918. };
  42919. /**
  42920. * Binds the given world matrix to the active effect
  42921. *
  42922. * @param world the matrix to bind
  42923. */
  42924. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42925. this._activeEffect.setMatrix("world", world);
  42926. };
  42927. /**
  42928. * Binds the given normal matrix to the active effect
  42929. *
  42930. * @param normalMatrix the matrix to bind
  42931. */
  42932. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42933. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42934. };
  42935. PushMaterial.prototype.bind = function (world, mesh) {
  42936. if (!mesh) {
  42937. return;
  42938. }
  42939. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42940. };
  42941. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42942. if (effect === void 0) { effect = null; }
  42943. _super.prototype._afterBind.call(this, mesh);
  42944. this.getScene()._cachedEffect = effect;
  42945. };
  42946. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42947. if (visibility === void 0) { visibility = 1; }
  42948. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42949. };
  42950. return PushMaterial;
  42951. }(BABYLON.Material));
  42952. BABYLON.PushMaterial = PushMaterial;
  42953. })(BABYLON || (BABYLON = {}));
  42954. //# sourceMappingURL=babylon.pushMaterial.js.map
  42955. var BABYLON;
  42956. (function (BABYLON) {
  42957. /** @hidden */
  42958. var StandardMaterialDefines = /** @class */ (function (_super) {
  42959. __extends(StandardMaterialDefines, _super);
  42960. function StandardMaterialDefines() {
  42961. var _this = _super.call(this) || this;
  42962. _this.MAINUV1 = false;
  42963. _this.MAINUV2 = false;
  42964. _this.DIFFUSE = false;
  42965. _this.DIFFUSEDIRECTUV = 0;
  42966. _this.AMBIENT = false;
  42967. _this.AMBIENTDIRECTUV = 0;
  42968. _this.OPACITY = false;
  42969. _this.OPACITYDIRECTUV = 0;
  42970. _this.OPACITYRGB = false;
  42971. _this.REFLECTION = false;
  42972. _this.EMISSIVE = false;
  42973. _this.EMISSIVEDIRECTUV = 0;
  42974. _this.SPECULAR = false;
  42975. _this.SPECULARDIRECTUV = 0;
  42976. _this.BUMP = false;
  42977. _this.BUMPDIRECTUV = 0;
  42978. _this.PARALLAX = false;
  42979. _this.PARALLAXOCCLUSION = false;
  42980. _this.SPECULAROVERALPHA = false;
  42981. _this.CLIPPLANE = false;
  42982. _this.ALPHATEST = false;
  42983. _this.DEPTHPREPASS = false;
  42984. _this.ALPHAFROMDIFFUSE = false;
  42985. _this.POINTSIZE = false;
  42986. _this.FOG = false;
  42987. _this.SPECULARTERM = false;
  42988. _this.DIFFUSEFRESNEL = false;
  42989. _this.OPACITYFRESNEL = false;
  42990. _this.REFLECTIONFRESNEL = false;
  42991. _this.REFRACTIONFRESNEL = false;
  42992. _this.EMISSIVEFRESNEL = false;
  42993. _this.FRESNEL = false;
  42994. _this.NORMAL = false;
  42995. _this.UV1 = false;
  42996. _this.UV2 = false;
  42997. _this.VERTEXCOLOR = false;
  42998. _this.VERTEXALPHA = false;
  42999. _this.NUM_BONE_INFLUENCERS = 0;
  43000. _this.BonesPerMesh = 0;
  43001. _this.INSTANCES = false;
  43002. _this.GLOSSINESS = false;
  43003. _this.ROUGHNESS = false;
  43004. _this.EMISSIVEASILLUMINATION = false;
  43005. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43006. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43007. _this.LIGHTMAP = false;
  43008. _this.LIGHTMAPDIRECTUV = 0;
  43009. _this.OBJECTSPACE_NORMALMAP = false;
  43010. _this.USELIGHTMAPASSHADOWMAP = false;
  43011. _this.REFLECTIONMAP_3D = false;
  43012. _this.REFLECTIONMAP_SPHERICAL = false;
  43013. _this.REFLECTIONMAP_PLANAR = false;
  43014. _this.REFLECTIONMAP_CUBIC = false;
  43015. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43016. _this.REFLECTIONMAP_PROJECTION = false;
  43017. _this.REFLECTIONMAP_SKYBOX = false;
  43018. _this.REFLECTIONMAP_EXPLICIT = false;
  43019. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43020. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43021. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43022. _this.INVERTCUBICMAP = false;
  43023. _this.LOGARITHMICDEPTH = false;
  43024. _this.REFRACTION = false;
  43025. _this.REFRACTIONMAP_3D = false;
  43026. _this.REFLECTIONOVERALPHA = false;
  43027. _this.TWOSIDEDLIGHTING = false;
  43028. _this.SHADOWFLOAT = false;
  43029. _this.MORPHTARGETS = false;
  43030. _this.MORPHTARGETS_NORMAL = false;
  43031. _this.MORPHTARGETS_TANGENT = false;
  43032. _this.NUM_MORPH_INFLUENCERS = 0;
  43033. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43034. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43035. _this.IMAGEPROCESSING = false;
  43036. _this.VIGNETTE = false;
  43037. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43038. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43039. _this.TONEMAPPING = false;
  43040. _this.CONTRAST = false;
  43041. _this.COLORCURVES = false;
  43042. _this.COLORGRADING = false;
  43043. _this.COLORGRADING3D = false;
  43044. _this.SAMPLER3DGREENDEPTH = false;
  43045. _this.SAMPLER3DBGRMAP = false;
  43046. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43047. /**
  43048. * If the reflection texture on this material is in linear color space
  43049. * @hidden
  43050. */
  43051. _this.IS_REFLECTION_LINEAR = false;
  43052. /**
  43053. * If the refraction texture on this material is in linear color space
  43054. * @hidden
  43055. */
  43056. _this.IS_REFRACTION_LINEAR = false;
  43057. _this.EXPOSURE = false;
  43058. _this.rebuild();
  43059. return _this;
  43060. }
  43061. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43062. var modes = [
  43063. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43064. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43065. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43066. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43067. ];
  43068. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43069. var mode = modes_1[_i];
  43070. this[mode] = (mode === modeToEnable);
  43071. }
  43072. };
  43073. return StandardMaterialDefines;
  43074. }(BABYLON.MaterialDefines));
  43075. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43076. var StandardMaterial = /** @class */ (function (_super) {
  43077. __extends(StandardMaterial, _super);
  43078. function StandardMaterial(name, scene) {
  43079. var _this = _super.call(this, name, scene) || this;
  43080. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43081. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43082. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43083. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43084. _this.specularPower = 64;
  43085. _this._useAlphaFromDiffuseTexture = false;
  43086. _this._useEmissiveAsIllumination = false;
  43087. _this._linkEmissiveWithDiffuse = false;
  43088. _this._useSpecularOverAlpha = false;
  43089. _this._useReflectionOverAlpha = false;
  43090. _this._disableLighting = false;
  43091. _this._useObjectSpaceNormalMap = false;
  43092. _this._useParallax = false;
  43093. _this._useParallaxOcclusion = false;
  43094. _this.parallaxScaleBias = 0.05;
  43095. _this._roughness = 0;
  43096. _this.indexOfRefraction = 0.98;
  43097. _this.invertRefractionY = true;
  43098. /**
  43099. * Defines the alpha limits in alpha test mode
  43100. */
  43101. _this.alphaCutOff = 0.4;
  43102. _this._useLightmapAsShadowmap = false;
  43103. _this._useReflectionFresnelFromSpecular = false;
  43104. _this._useGlossinessFromSpecularMapAlpha = false;
  43105. _this._maxSimultaneousLights = 4;
  43106. /**
  43107. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43108. */
  43109. _this._invertNormalMapX = false;
  43110. /**
  43111. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43112. */
  43113. _this._invertNormalMapY = false;
  43114. /**
  43115. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43116. */
  43117. _this._twoSidedLighting = false;
  43118. _this._renderTargets = new BABYLON.SmartArray(16);
  43119. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43120. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43121. // Setup the default processing configuration to the scene.
  43122. _this._attachImageProcessingConfiguration(null);
  43123. _this.getRenderTargetTextures = function () {
  43124. _this._renderTargets.reset();
  43125. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43126. _this._renderTargets.push(_this._reflectionTexture);
  43127. }
  43128. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43129. _this._renderTargets.push(_this._refractionTexture);
  43130. }
  43131. return _this._renderTargets;
  43132. };
  43133. return _this;
  43134. }
  43135. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43136. /**
  43137. * Gets the image processing configuration used either in this material.
  43138. */
  43139. get: function () {
  43140. return this._imageProcessingConfiguration;
  43141. },
  43142. /**
  43143. * Sets the Default image processing configuration used either in the this material.
  43144. *
  43145. * If sets to null, the scene one is in use.
  43146. */
  43147. set: function (value) {
  43148. this._attachImageProcessingConfiguration(value);
  43149. // Ensure the effect will be rebuilt.
  43150. this._markAllSubMeshesAsTexturesDirty();
  43151. },
  43152. enumerable: true,
  43153. configurable: true
  43154. });
  43155. /**
  43156. * Attaches a new image processing configuration to the Standard Material.
  43157. * @param configuration
  43158. */
  43159. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43160. var _this = this;
  43161. if (configuration === this._imageProcessingConfiguration) {
  43162. return;
  43163. }
  43164. // Detaches observer.
  43165. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43166. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43167. }
  43168. // Pick the scene configuration if needed.
  43169. if (!configuration) {
  43170. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43171. }
  43172. else {
  43173. this._imageProcessingConfiguration = configuration;
  43174. }
  43175. // Attaches observer.
  43176. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43177. _this._markAllSubMeshesAsImageProcessingDirty();
  43178. });
  43179. };
  43180. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43181. /**
  43182. * Gets wether the color curves effect is enabled.
  43183. */
  43184. get: function () {
  43185. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43186. },
  43187. /**
  43188. * Sets wether the color curves effect is enabled.
  43189. */
  43190. set: function (value) {
  43191. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43192. },
  43193. enumerable: true,
  43194. configurable: true
  43195. });
  43196. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43197. /**
  43198. * Gets wether the color grading effect is enabled.
  43199. */
  43200. get: function () {
  43201. return this.imageProcessingConfiguration.colorGradingEnabled;
  43202. },
  43203. /**
  43204. * Gets wether the color grading effect is enabled.
  43205. */
  43206. set: function (value) {
  43207. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43208. },
  43209. enumerable: true,
  43210. configurable: true
  43211. });
  43212. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43213. /**
  43214. * Gets wether tonemapping is enabled or not.
  43215. */
  43216. get: function () {
  43217. return this._imageProcessingConfiguration.toneMappingEnabled;
  43218. },
  43219. /**
  43220. * Sets wether tonemapping is enabled or not
  43221. */
  43222. set: function (value) {
  43223. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43224. },
  43225. enumerable: true,
  43226. configurable: true
  43227. });
  43228. ;
  43229. ;
  43230. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43231. /**
  43232. * The camera exposure used on this material.
  43233. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43234. * This corresponds to a photographic exposure.
  43235. */
  43236. get: function () {
  43237. return this._imageProcessingConfiguration.exposure;
  43238. },
  43239. /**
  43240. * The camera exposure used on this material.
  43241. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43242. * This corresponds to a photographic exposure.
  43243. */
  43244. set: function (value) {
  43245. this._imageProcessingConfiguration.exposure = value;
  43246. },
  43247. enumerable: true,
  43248. configurable: true
  43249. });
  43250. ;
  43251. ;
  43252. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43253. /**
  43254. * Gets The camera contrast used on this material.
  43255. */
  43256. get: function () {
  43257. return this._imageProcessingConfiguration.contrast;
  43258. },
  43259. /**
  43260. * Sets The camera contrast used on this material.
  43261. */
  43262. set: function (value) {
  43263. this._imageProcessingConfiguration.contrast = value;
  43264. },
  43265. enumerable: true,
  43266. configurable: true
  43267. });
  43268. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43269. /**
  43270. * Gets the Color Grading 2D Lookup Texture.
  43271. */
  43272. get: function () {
  43273. return this._imageProcessingConfiguration.colorGradingTexture;
  43274. },
  43275. /**
  43276. * Sets the Color Grading 2D Lookup Texture.
  43277. */
  43278. set: function (value) {
  43279. this._imageProcessingConfiguration.colorGradingTexture = value;
  43280. },
  43281. enumerable: true,
  43282. configurable: true
  43283. });
  43284. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43285. /**
  43286. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43287. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43288. * 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;
  43289. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43290. */
  43291. get: function () {
  43292. return this._imageProcessingConfiguration.colorCurves;
  43293. },
  43294. /**
  43295. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43296. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43297. * 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;
  43298. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43299. */
  43300. set: function (value) {
  43301. this._imageProcessingConfiguration.colorCurves = value;
  43302. },
  43303. enumerable: true,
  43304. configurable: true
  43305. });
  43306. StandardMaterial.prototype.getClassName = function () {
  43307. return "StandardMaterial";
  43308. };
  43309. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43310. get: function () {
  43311. return this._useLogarithmicDepth;
  43312. },
  43313. set: function (value) {
  43314. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43315. this._markAllSubMeshesAsMiscDirty();
  43316. },
  43317. enumerable: true,
  43318. configurable: true
  43319. });
  43320. StandardMaterial.prototype.needAlphaBlending = function () {
  43321. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43322. };
  43323. StandardMaterial.prototype.needAlphaTesting = function () {
  43324. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43325. };
  43326. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43327. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43328. };
  43329. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43330. return this._diffuseTexture;
  43331. };
  43332. /**
  43333. * Child classes can use it to update shaders
  43334. */
  43335. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43336. if (useInstances === void 0) { useInstances = false; }
  43337. if (subMesh.effect && this.isFrozen) {
  43338. if (this._wasPreviouslyReady && subMesh.effect) {
  43339. return true;
  43340. }
  43341. }
  43342. if (!subMesh._materialDefines) {
  43343. subMesh._materialDefines = new StandardMaterialDefines();
  43344. }
  43345. var scene = this.getScene();
  43346. var defines = subMesh._materialDefines;
  43347. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43348. if (defines._renderId === scene.getRenderId()) {
  43349. return true;
  43350. }
  43351. }
  43352. var engine = scene.getEngine();
  43353. // Lights
  43354. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43355. // Textures
  43356. if (defines._areTexturesDirty) {
  43357. defines._needUVs = false;
  43358. defines.MAINUV1 = false;
  43359. defines.MAINUV2 = false;
  43360. if (scene.texturesEnabled) {
  43361. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43362. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43363. return false;
  43364. }
  43365. else {
  43366. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43367. }
  43368. }
  43369. else {
  43370. defines.DIFFUSE = false;
  43371. }
  43372. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43373. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43374. return false;
  43375. }
  43376. else {
  43377. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43378. }
  43379. }
  43380. else {
  43381. defines.AMBIENT = false;
  43382. }
  43383. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43384. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43385. return false;
  43386. }
  43387. else {
  43388. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43389. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43390. }
  43391. }
  43392. else {
  43393. defines.OPACITY = false;
  43394. }
  43395. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43396. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43397. return false;
  43398. }
  43399. else {
  43400. defines._needNormals = true;
  43401. defines.REFLECTION = true;
  43402. defines.ROUGHNESS = (this._roughness > 0);
  43403. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43404. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43405. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43406. switch (this._reflectionTexture.coordinatesMode) {
  43407. case BABYLON.Texture.EXPLICIT_MODE:
  43408. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43409. break;
  43410. case BABYLON.Texture.PLANAR_MODE:
  43411. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43412. break;
  43413. case BABYLON.Texture.PROJECTION_MODE:
  43414. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43415. break;
  43416. case BABYLON.Texture.SKYBOX_MODE:
  43417. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43418. break;
  43419. case BABYLON.Texture.SPHERICAL_MODE:
  43420. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43421. break;
  43422. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43423. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43424. break;
  43425. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43426. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43427. break;
  43428. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43429. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43430. break;
  43431. case BABYLON.Texture.CUBIC_MODE:
  43432. case BABYLON.Texture.INVCUBIC_MODE:
  43433. default:
  43434. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43435. break;
  43436. }
  43437. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43438. }
  43439. }
  43440. else {
  43441. defines.REFLECTION = false;
  43442. }
  43443. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43444. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43445. return false;
  43446. }
  43447. else {
  43448. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43449. }
  43450. }
  43451. else {
  43452. defines.EMISSIVE = false;
  43453. }
  43454. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43455. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43456. return false;
  43457. }
  43458. else {
  43459. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43460. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43461. }
  43462. }
  43463. else {
  43464. defines.LIGHTMAP = false;
  43465. }
  43466. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43467. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43468. return false;
  43469. }
  43470. else {
  43471. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43472. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43473. }
  43474. }
  43475. else {
  43476. defines.SPECULAR = false;
  43477. }
  43478. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43479. // Bump texure can not be not blocking.
  43480. if (!this._bumpTexture.isReady()) {
  43481. return false;
  43482. }
  43483. else {
  43484. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43485. defines.PARALLAX = this._useParallax;
  43486. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43487. }
  43488. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43489. }
  43490. else {
  43491. defines.BUMP = false;
  43492. }
  43493. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43494. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43495. return false;
  43496. }
  43497. else {
  43498. defines._needUVs = true;
  43499. defines.REFRACTION = true;
  43500. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43501. }
  43502. }
  43503. else {
  43504. defines.REFRACTION = false;
  43505. }
  43506. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43507. }
  43508. else {
  43509. defines.DIFFUSE = false;
  43510. defines.AMBIENT = false;
  43511. defines.OPACITY = false;
  43512. defines.REFLECTION = false;
  43513. defines.EMISSIVE = false;
  43514. defines.LIGHTMAP = false;
  43515. defines.BUMP = false;
  43516. defines.REFRACTION = false;
  43517. }
  43518. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43519. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43520. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43521. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43522. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43523. }
  43524. if (defines._areImageProcessingDirty) {
  43525. if (!this._imageProcessingConfiguration.isReady()) {
  43526. return false;
  43527. }
  43528. this._imageProcessingConfiguration.prepareDefines(defines);
  43529. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43530. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43531. }
  43532. if (defines._areFresnelDirty) {
  43533. if (StandardMaterial.FresnelEnabled) {
  43534. // Fresnel
  43535. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43536. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43537. this._reflectionFresnelParameters) {
  43538. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43539. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43540. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43541. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43542. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43543. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43544. defines._needNormals = true;
  43545. defines.FRESNEL = true;
  43546. }
  43547. }
  43548. else {
  43549. defines.FRESNEL = false;
  43550. }
  43551. }
  43552. // Misc.
  43553. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43554. // Attribs
  43555. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43556. // Values that need to be evaluated on every frame
  43557. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43558. // Get correct effect
  43559. if (defines.isDirty) {
  43560. defines.markAsProcessed();
  43561. scene.resetCachedMaterial();
  43562. // Fallbacks
  43563. var fallbacks = new BABYLON.EffectFallbacks();
  43564. if (defines.REFLECTION) {
  43565. fallbacks.addFallback(0, "REFLECTION");
  43566. }
  43567. if (defines.SPECULAR) {
  43568. fallbacks.addFallback(0, "SPECULAR");
  43569. }
  43570. if (defines.BUMP) {
  43571. fallbacks.addFallback(0, "BUMP");
  43572. }
  43573. if (defines.PARALLAX) {
  43574. fallbacks.addFallback(1, "PARALLAX");
  43575. }
  43576. if (defines.PARALLAXOCCLUSION) {
  43577. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43578. }
  43579. if (defines.SPECULAROVERALPHA) {
  43580. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43581. }
  43582. if (defines.FOG) {
  43583. fallbacks.addFallback(1, "FOG");
  43584. }
  43585. if (defines.POINTSIZE) {
  43586. fallbacks.addFallback(0, "POINTSIZE");
  43587. }
  43588. if (defines.LOGARITHMICDEPTH) {
  43589. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43590. }
  43591. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43592. if (defines.SPECULARTERM) {
  43593. fallbacks.addFallback(0, "SPECULARTERM");
  43594. }
  43595. if (defines.DIFFUSEFRESNEL) {
  43596. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43597. }
  43598. if (defines.OPACITYFRESNEL) {
  43599. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43600. }
  43601. if (defines.REFLECTIONFRESNEL) {
  43602. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43603. }
  43604. if (defines.EMISSIVEFRESNEL) {
  43605. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43606. }
  43607. if (defines.FRESNEL) {
  43608. fallbacks.addFallback(4, "FRESNEL");
  43609. }
  43610. //Attributes
  43611. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43612. if (defines.NORMAL) {
  43613. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43614. }
  43615. if (defines.UV1) {
  43616. attribs.push(BABYLON.VertexBuffer.UVKind);
  43617. }
  43618. if (defines.UV2) {
  43619. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43620. }
  43621. if (defines.VERTEXCOLOR) {
  43622. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43623. }
  43624. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43625. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43626. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43627. var shaderName = "default";
  43628. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43629. "vFogInfos", "vFogColor", "pointSize",
  43630. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43631. "mBones",
  43632. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43633. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43634. "vReflectionPosition", "vReflectionSize",
  43635. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43636. ];
  43637. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43638. var uniformBuffers = ["Material", "Scene"];
  43639. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43640. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43641. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43642. uniformsNames: uniforms,
  43643. uniformBuffersNames: uniformBuffers,
  43644. samplers: samplers,
  43645. defines: defines,
  43646. maxSimultaneousLights: this._maxSimultaneousLights
  43647. });
  43648. if (this.customShaderNameResolve) {
  43649. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43650. }
  43651. var join = defines.toString();
  43652. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43653. attributes: attribs,
  43654. uniformsNames: uniforms,
  43655. uniformBuffersNames: uniformBuffers,
  43656. samplers: samplers,
  43657. defines: join,
  43658. fallbacks: fallbacks,
  43659. onCompiled: this.onCompiled,
  43660. onError: this.onError,
  43661. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43662. }, engine), defines);
  43663. this.buildUniformLayout();
  43664. }
  43665. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43666. return false;
  43667. }
  43668. defines._renderId = scene.getRenderId();
  43669. this._wasPreviouslyReady = true;
  43670. return true;
  43671. };
  43672. StandardMaterial.prototype.buildUniformLayout = function () {
  43673. // Order is important !
  43674. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43675. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43676. this._uniformBuffer.addUniform("opacityParts", 4);
  43677. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43678. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43679. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43680. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43681. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43682. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43683. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43684. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43685. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43686. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43687. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43688. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43689. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43690. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43691. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43692. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43693. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43694. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43695. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43696. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43697. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43698. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43699. this._uniformBuffer.addUniform("specularMatrix", 16);
  43700. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43701. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43702. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43703. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43704. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43705. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43706. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43707. this._uniformBuffer.addUniform("pointSize", 1);
  43708. this._uniformBuffer.create();
  43709. };
  43710. StandardMaterial.prototype.unbind = function () {
  43711. if (this._activeEffect) {
  43712. var needFlag = false;
  43713. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43714. this._activeEffect.setTexture("reflection2DSampler", null);
  43715. needFlag = true;
  43716. }
  43717. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43718. this._activeEffect.setTexture("refraction2DSampler", null);
  43719. needFlag = true;
  43720. }
  43721. if (needFlag) {
  43722. this._markAllSubMeshesAsTexturesDirty();
  43723. }
  43724. }
  43725. _super.prototype.unbind.call(this);
  43726. };
  43727. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43728. var scene = this.getScene();
  43729. var defines = subMesh._materialDefines;
  43730. if (!defines) {
  43731. return;
  43732. }
  43733. var effect = subMesh.effect;
  43734. if (!effect) {
  43735. return;
  43736. }
  43737. this._activeEffect = effect;
  43738. // Matrices
  43739. this.bindOnlyWorldMatrix(world);
  43740. // Normal Matrix
  43741. if (defines.OBJECTSPACE_NORMALMAP) {
  43742. world.toNormalMatrix(this._normalMatrix);
  43743. this.bindOnlyNormalMatrix(this._normalMatrix);
  43744. }
  43745. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43746. // Bones
  43747. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43748. if (mustRebind) {
  43749. this._uniformBuffer.bindToEffect(effect, "Material");
  43750. this.bindViewProjection(effect);
  43751. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43752. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43753. // Fresnel
  43754. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43755. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43756. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43757. }
  43758. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43759. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43760. }
  43761. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43762. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43763. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43764. }
  43765. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43766. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43767. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43768. }
  43769. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43770. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43771. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43772. }
  43773. }
  43774. // Textures
  43775. if (scene.texturesEnabled) {
  43776. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43777. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43778. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43779. if (this._diffuseTexture.hasAlpha) {
  43780. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43781. }
  43782. }
  43783. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43784. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43785. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43786. }
  43787. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43788. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43789. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43790. }
  43791. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43792. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43793. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43794. if (this._reflectionTexture.boundingBoxSize) {
  43795. var cubeTexture = this._reflectionTexture;
  43796. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43797. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43798. }
  43799. }
  43800. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43801. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43802. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43803. }
  43804. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43805. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43806. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43807. }
  43808. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43809. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43810. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43811. }
  43812. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43813. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43814. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43815. if (scene._mirroredCameraPosition) {
  43816. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43817. }
  43818. else {
  43819. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43820. }
  43821. }
  43822. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43823. var depth = 1.0;
  43824. if (!this._refractionTexture.isCube) {
  43825. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43826. if (this._refractionTexture.depth) {
  43827. depth = this._refractionTexture.depth;
  43828. }
  43829. }
  43830. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43831. }
  43832. }
  43833. // Point size
  43834. if (this.pointsCloud) {
  43835. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43836. }
  43837. if (defines.SPECULARTERM) {
  43838. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43839. }
  43840. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43841. // Diffuse
  43842. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43843. }
  43844. // Textures
  43845. if (scene.texturesEnabled) {
  43846. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43847. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43848. }
  43849. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43850. effect.setTexture("ambientSampler", this._ambientTexture);
  43851. }
  43852. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43853. effect.setTexture("opacitySampler", this._opacityTexture);
  43854. }
  43855. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43856. if (this._reflectionTexture.isCube) {
  43857. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43858. }
  43859. else {
  43860. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43861. }
  43862. }
  43863. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43864. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43865. }
  43866. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43867. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43868. }
  43869. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43870. effect.setTexture("specularSampler", this._specularTexture);
  43871. }
  43872. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43873. effect.setTexture("bumpSampler", this._bumpTexture);
  43874. }
  43875. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43876. var depth = 1.0;
  43877. if (this._refractionTexture.isCube) {
  43878. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43879. }
  43880. else {
  43881. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43882. }
  43883. }
  43884. }
  43885. // Clip plane
  43886. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43887. // Colors
  43888. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43889. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43890. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43891. }
  43892. if (mustRebind || !this.isFrozen) {
  43893. // Lights
  43894. if (scene.lightsEnabled && !this._disableLighting) {
  43895. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43896. }
  43897. // View
  43898. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43899. this.bindView(effect);
  43900. }
  43901. // Fog
  43902. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43903. // Morph targets
  43904. if (defines.NUM_MORPH_INFLUENCERS) {
  43905. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43906. }
  43907. // Log. depth
  43908. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43909. // image processing
  43910. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43911. this._imageProcessingConfiguration.bind(this._activeEffect);
  43912. }
  43913. }
  43914. this._uniformBuffer.update();
  43915. this._afterBind(mesh, this._activeEffect);
  43916. };
  43917. StandardMaterial.prototype.getAnimatables = function () {
  43918. var results = [];
  43919. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43920. results.push(this._diffuseTexture);
  43921. }
  43922. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43923. results.push(this._ambientTexture);
  43924. }
  43925. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43926. results.push(this._opacityTexture);
  43927. }
  43928. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43929. results.push(this._reflectionTexture);
  43930. }
  43931. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43932. results.push(this._emissiveTexture);
  43933. }
  43934. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43935. results.push(this._specularTexture);
  43936. }
  43937. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43938. results.push(this._bumpTexture);
  43939. }
  43940. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43941. results.push(this._lightmapTexture);
  43942. }
  43943. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43944. results.push(this._refractionTexture);
  43945. }
  43946. return results;
  43947. };
  43948. StandardMaterial.prototype.getActiveTextures = function () {
  43949. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43950. if (this._diffuseTexture) {
  43951. activeTextures.push(this._diffuseTexture);
  43952. }
  43953. if (this._ambientTexture) {
  43954. activeTextures.push(this._ambientTexture);
  43955. }
  43956. if (this._opacityTexture) {
  43957. activeTextures.push(this._opacityTexture);
  43958. }
  43959. if (this._reflectionTexture) {
  43960. activeTextures.push(this._reflectionTexture);
  43961. }
  43962. if (this._emissiveTexture) {
  43963. activeTextures.push(this._emissiveTexture);
  43964. }
  43965. if (this._specularTexture) {
  43966. activeTextures.push(this._specularTexture);
  43967. }
  43968. if (this._bumpTexture) {
  43969. activeTextures.push(this._bumpTexture);
  43970. }
  43971. if (this._lightmapTexture) {
  43972. activeTextures.push(this._lightmapTexture);
  43973. }
  43974. if (this._refractionTexture) {
  43975. activeTextures.push(this._refractionTexture);
  43976. }
  43977. return activeTextures;
  43978. };
  43979. StandardMaterial.prototype.hasTexture = function (texture) {
  43980. if (_super.prototype.hasTexture.call(this, texture)) {
  43981. return true;
  43982. }
  43983. if (this._diffuseTexture === texture) {
  43984. return true;
  43985. }
  43986. if (this._ambientTexture === texture) {
  43987. return true;
  43988. }
  43989. if (this._opacityTexture === texture) {
  43990. return true;
  43991. }
  43992. if (this._reflectionTexture === texture) {
  43993. return true;
  43994. }
  43995. if (this._emissiveTexture === texture) {
  43996. return true;
  43997. }
  43998. if (this._specularTexture === texture) {
  43999. return true;
  44000. }
  44001. if (this._bumpTexture === texture) {
  44002. return true;
  44003. }
  44004. if (this._lightmapTexture === texture) {
  44005. return true;
  44006. }
  44007. if (this._refractionTexture === texture) {
  44008. return true;
  44009. }
  44010. return false;
  44011. };
  44012. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44013. if (forceDisposeTextures) {
  44014. if (this._diffuseTexture) {
  44015. this._diffuseTexture.dispose();
  44016. }
  44017. if (this._ambientTexture) {
  44018. this._ambientTexture.dispose();
  44019. }
  44020. if (this._opacityTexture) {
  44021. this._opacityTexture.dispose();
  44022. }
  44023. if (this._reflectionTexture) {
  44024. this._reflectionTexture.dispose();
  44025. }
  44026. if (this._emissiveTexture) {
  44027. this._emissiveTexture.dispose();
  44028. }
  44029. if (this._specularTexture) {
  44030. this._specularTexture.dispose();
  44031. }
  44032. if (this._bumpTexture) {
  44033. this._bumpTexture.dispose();
  44034. }
  44035. if (this._lightmapTexture) {
  44036. this._lightmapTexture.dispose();
  44037. }
  44038. if (this._refractionTexture) {
  44039. this._refractionTexture.dispose();
  44040. }
  44041. }
  44042. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44043. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44044. }
  44045. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44046. };
  44047. StandardMaterial.prototype.clone = function (name) {
  44048. var _this = this;
  44049. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44050. result.name = name;
  44051. result.id = name;
  44052. return result;
  44053. };
  44054. StandardMaterial.prototype.serialize = function () {
  44055. return BABYLON.SerializationHelper.Serialize(this);
  44056. };
  44057. // Statics
  44058. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44059. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44060. };
  44061. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44062. get: function () {
  44063. return StandardMaterial._DiffuseTextureEnabled;
  44064. },
  44065. set: function (value) {
  44066. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44067. return;
  44068. }
  44069. StandardMaterial._DiffuseTextureEnabled = value;
  44070. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44071. },
  44072. enumerable: true,
  44073. configurable: true
  44074. });
  44075. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44076. get: function () {
  44077. return StandardMaterial._AmbientTextureEnabled;
  44078. },
  44079. set: function (value) {
  44080. if (StandardMaterial._AmbientTextureEnabled === value) {
  44081. return;
  44082. }
  44083. StandardMaterial._AmbientTextureEnabled = value;
  44084. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44085. },
  44086. enumerable: true,
  44087. configurable: true
  44088. });
  44089. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44090. get: function () {
  44091. return StandardMaterial._OpacityTextureEnabled;
  44092. },
  44093. set: function (value) {
  44094. if (StandardMaterial._OpacityTextureEnabled === value) {
  44095. return;
  44096. }
  44097. StandardMaterial._OpacityTextureEnabled = value;
  44098. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44099. },
  44100. enumerable: true,
  44101. configurable: true
  44102. });
  44103. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44104. get: function () {
  44105. return StandardMaterial._ReflectionTextureEnabled;
  44106. },
  44107. set: function (value) {
  44108. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44109. return;
  44110. }
  44111. StandardMaterial._ReflectionTextureEnabled = value;
  44112. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44113. },
  44114. enumerable: true,
  44115. configurable: true
  44116. });
  44117. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44118. get: function () {
  44119. return StandardMaterial._EmissiveTextureEnabled;
  44120. },
  44121. set: function (value) {
  44122. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44123. return;
  44124. }
  44125. StandardMaterial._EmissiveTextureEnabled = value;
  44126. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44127. },
  44128. enumerable: true,
  44129. configurable: true
  44130. });
  44131. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44132. get: function () {
  44133. return StandardMaterial._SpecularTextureEnabled;
  44134. },
  44135. set: function (value) {
  44136. if (StandardMaterial._SpecularTextureEnabled === value) {
  44137. return;
  44138. }
  44139. StandardMaterial._SpecularTextureEnabled = value;
  44140. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44141. },
  44142. enumerable: true,
  44143. configurable: true
  44144. });
  44145. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44146. get: function () {
  44147. return StandardMaterial._BumpTextureEnabled;
  44148. },
  44149. set: function (value) {
  44150. if (StandardMaterial._BumpTextureEnabled === value) {
  44151. return;
  44152. }
  44153. StandardMaterial._BumpTextureEnabled = value;
  44154. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44155. },
  44156. enumerable: true,
  44157. configurable: true
  44158. });
  44159. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44160. get: function () {
  44161. return StandardMaterial._LightmapTextureEnabled;
  44162. },
  44163. set: function (value) {
  44164. if (StandardMaterial._LightmapTextureEnabled === value) {
  44165. return;
  44166. }
  44167. StandardMaterial._LightmapTextureEnabled = value;
  44168. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44169. },
  44170. enumerable: true,
  44171. configurable: true
  44172. });
  44173. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44174. get: function () {
  44175. return StandardMaterial._RefractionTextureEnabled;
  44176. },
  44177. set: function (value) {
  44178. if (StandardMaterial._RefractionTextureEnabled === value) {
  44179. return;
  44180. }
  44181. StandardMaterial._RefractionTextureEnabled = value;
  44182. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44183. },
  44184. enumerable: true,
  44185. configurable: true
  44186. });
  44187. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44188. get: function () {
  44189. return StandardMaterial._ColorGradingTextureEnabled;
  44190. },
  44191. set: function (value) {
  44192. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44193. return;
  44194. }
  44195. StandardMaterial._ColorGradingTextureEnabled = value;
  44196. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44197. },
  44198. enumerable: true,
  44199. configurable: true
  44200. });
  44201. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44202. get: function () {
  44203. return StandardMaterial._FresnelEnabled;
  44204. },
  44205. set: function (value) {
  44206. if (StandardMaterial._FresnelEnabled === value) {
  44207. return;
  44208. }
  44209. StandardMaterial._FresnelEnabled = value;
  44210. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44211. },
  44212. enumerable: true,
  44213. configurable: true
  44214. });
  44215. // Flags used to enable or disable a type of texture for all Standard Materials
  44216. StandardMaterial._DiffuseTextureEnabled = true;
  44217. StandardMaterial._AmbientTextureEnabled = true;
  44218. StandardMaterial._OpacityTextureEnabled = true;
  44219. StandardMaterial._ReflectionTextureEnabled = true;
  44220. StandardMaterial._EmissiveTextureEnabled = true;
  44221. StandardMaterial._SpecularTextureEnabled = true;
  44222. StandardMaterial._BumpTextureEnabled = true;
  44223. StandardMaterial._LightmapTextureEnabled = true;
  44224. StandardMaterial._RefractionTextureEnabled = true;
  44225. StandardMaterial._ColorGradingTextureEnabled = true;
  44226. StandardMaterial._FresnelEnabled = true;
  44227. __decorate([
  44228. BABYLON.serializeAsTexture("diffuseTexture")
  44229. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44230. __decorate([
  44231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44232. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44233. __decorate([
  44234. BABYLON.serializeAsTexture("ambientTexture")
  44235. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44236. __decorate([
  44237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44238. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44239. __decorate([
  44240. BABYLON.serializeAsTexture("opacityTexture")
  44241. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44242. __decorate([
  44243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44244. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44245. __decorate([
  44246. BABYLON.serializeAsTexture("reflectionTexture")
  44247. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44248. __decorate([
  44249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44250. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44251. __decorate([
  44252. BABYLON.serializeAsTexture("emissiveTexture")
  44253. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44254. __decorate([
  44255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44256. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44257. __decorate([
  44258. BABYLON.serializeAsTexture("specularTexture")
  44259. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44260. __decorate([
  44261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44262. ], StandardMaterial.prototype, "specularTexture", void 0);
  44263. __decorate([
  44264. BABYLON.serializeAsTexture("bumpTexture")
  44265. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44266. __decorate([
  44267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44268. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44269. __decorate([
  44270. BABYLON.serializeAsTexture("lightmapTexture")
  44271. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44272. __decorate([
  44273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44274. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44275. __decorate([
  44276. BABYLON.serializeAsTexture("refractionTexture")
  44277. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44278. __decorate([
  44279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44280. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44281. __decorate([
  44282. BABYLON.serializeAsColor3("ambient")
  44283. ], StandardMaterial.prototype, "ambientColor", void 0);
  44284. __decorate([
  44285. BABYLON.serializeAsColor3("diffuse")
  44286. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44287. __decorate([
  44288. BABYLON.serializeAsColor3("specular")
  44289. ], StandardMaterial.prototype, "specularColor", void 0);
  44290. __decorate([
  44291. BABYLON.serializeAsColor3("emissive")
  44292. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44293. __decorate([
  44294. BABYLON.serialize()
  44295. ], StandardMaterial.prototype, "specularPower", void 0);
  44296. __decorate([
  44297. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44298. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44299. __decorate([
  44300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44301. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44302. __decorate([
  44303. BABYLON.serialize("useEmissiveAsIllumination")
  44304. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44305. __decorate([
  44306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44307. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44308. __decorate([
  44309. BABYLON.serialize("linkEmissiveWithDiffuse")
  44310. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44311. __decorate([
  44312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44313. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44314. __decorate([
  44315. BABYLON.serialize("useSpecularOverAlpha")
  44316. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44317. __decorate([
  44318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44319. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44320. __decorate([
  44321. BABYLON.serialize("useReflectionOverAlpha")
  44322. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44323. __decorate([
  44324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44325. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44326. __decorate([
  44327. BABYLON.serialize("disableLighting")
  44328. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44329. __decorate([
  44330. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44331. ], StandardMaterial.prototype, "disableLighting", void 0);
  44332. __decorate([
  44333. BABYLON.serialize("useObjectSpaceNormalMap")
  44334. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44335. __decorate([
  44336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44337. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44338. __decorate([
  44339. BABYLON.serialize("useParallax")
  44340. ], StandardMaterial.prototype, "_useParallax", void 0);
  44341. __decorate([
  44342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44343. ], StandardMaterial.prototype, "useParallax", void 0);
  44344. __decorate([
  44345. BABYLON.serialize("useParallaxOcclusion")
  44346. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44347. __decorate([
  44348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44349. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44350. __decorate([
  44351. BABYLON.serialize()
  44352. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44353. __decorate([
  44354. BABYLON.serialize("roughness")
  44355. ], StandardMaterial.prototype, "_roughness", void 0);
  44356. __decorate([
  44357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44358. ], StandardMaterial.prototype, "roughness", void 0);
  44359. __decorate([
  44360. BABYLON.serialize()
  44361. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44362. __decorate([
  44363. BABYLON.serialize()
  44364. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44365. __decorate([
  44366. BABYLON.serialize()
  44367. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44368. __decorate([
  44369. BABYLON.serialize("useLightmapAsShadowmap")
  44370. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44371. __decorate([
  44372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44373. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44374. __decorate([
  44375. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44376. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44377. __decorate([
  44378. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44379. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44380. __decorate([
  44381. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44382. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44383. __decorate([
  44384. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44385. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44386. __decorate([
  44387. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44388. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44389. __decorate([
  44390. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44391. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44392. __decorate([
  44393. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44394. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44395. __decorate([
  44396. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44397. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44398. __decorate([
  44399. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44400. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44401. __decorate([
  44402. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44403. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44404. __decorate([
  44405. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44406. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44407. __decorate([
  44408. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44409. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44410. __decorate([
  44411. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44412. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44413. __decorate([
  44414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44415. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44416. __decorate([
  44417. BABYLON.serialize("maxSimultaneousLights")
  44418. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44419. __decorate([
  44420. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44421. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44422. __decorate([
  44423. BABYLON.serialize("invertNormalMapX")
  44424. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44425. __decorate([
  44426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44427. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44428. __decorate([
  44429. BABYLON.serialize("invertNormalMapY")
  44430. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44431. __decorate([
  44432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44433. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44434. __decorate([
  44435. BABYLON.serialize("twoSidedLighting")
  44436. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44437. __decorate([
  44438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44439. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44440. __decorate([
  44441. BABYLON.serialize()
  44442. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44443. return StandardMaterial;
  44444. }(BABYLON.PushMaterial));
  44445. BABYLON.StandardMaterial = StandardMaterial;
  44446. })(BABYLON || (BABYLON = {}));
  44447. //# sourceMappingURL=babylon.standardMaterial.js.map
  44448. var BABYLON;
  44449. (function (BABYLON) {
  44450. /**
  44451. * Manages the defines for the PBR Material.
  44452. * @hiddenChildren
  44453. */
  44454. var PBRMaterialDefines = /** @class */ (function (_super) {
  44455. __extends(PBRMaterialDefines, _super);
  44456. /**
  44457. * Initializes the PBR Material defines.
  44458. */
  44459. function PBRMaterialDefines() {
  44460. var _this = _super.call(this) || this;
  44461. _this.PBR = true;
  44462. _this.MAINUV1 = false;
  44463. _this.MAINUV2 = false;
  44464. _this.UV1 = false;
  44465. _this.UV2 = false;
  44466. _this.ALBEDO = false;
  44467. _this.ALBEDODIRECTUV = 0;
  44468. _this.VERTEXCOLOR = false;
  44469. _this.AMBIENT = false;
  44470. _this.AMBIENTDIRECTUV = 0;
  44471. _this.AMBIENTINGRAYSCALE = false;
  44472. _this.OPACITY = false;
  44473. _this.VERTEXALPHA = false;
  44474. _this.OPACITYDIRECTUV = 0;
  44475. _this.OPACITYRGB = false;
  44476. _this.ALPHATEST = false;
  44477. _this.DEPTHPREPASS = false;
  44478. _this.ALPHABLEND = false;
  44479. _this.ALPHAFROMALBEDO = false;
  44480. _this.ALPHATESTVALUE = "0.5";
  44481. _this.SPECULAROVERALPHA = false;
  44482. _this.RADIANCEOVERALPHA = false;
  44483. _this.ALPHAFRESNEL = false;
  44484. _this.LINEARALPHAFRESNEL = false;
  44485. _this.PREMULTIPLYALPHA = false;
  44486. _this.EMISSIVE = false;
  44487. _this.EMISSIVEDIRECTUV = 0;
  44488. _this.REFLECTIVITY = false;
  44489. _this.REFLECTIVITYDIRECTUV = 0;
  44490. _this.SPECULARTERM = false;
  44491. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44492. _this.MICROSURFACEAUTOMATIC = false;
  44493. _this.LODBASEDMICROSFURACE = false;
  44494. _this.MICROSURFACEMAP = false;
  44495. _this.MICROSURFACEMAPDIRECTUV = 0;
  44496. _this.METALLICWORKFLOW = false;
  44497. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44498. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44499. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44500. _this.AOSTOREINMETALMAPRED = false;
  44501. _this.ENVIRONMENTBRDF = false;
  44502. _this.NORMAL = false;
  44503. _this.TANGENT = false;
  44504. _this.BUMP = false;
  44505. _this.BUMPDIRECTUV = 0;
  44506. _this.OBJECTSPACE_NORMALMAP = false;
  44507. _this.PARALLAX = false;
  44508. _this.PARALLAXOCCLUSION = false;
  44509. _this.NORMALXYSCALE = true;
  44510. _this.LIGHTMAP = false;
  44511. _this.LIGHTMAPDIRECTUV = 0;
  44512. _this.USELIGHTMAPASSHADOWMAP = false;
  44513. _this.GAMMALIGHTMAP = false;
  44514. _this.REFLECTION = false;
  44515. _this.REFLECTIONMAP_3D = false;
  44516. _this.REFLECTIONMAP_SPHERICAL = false;
  44517. _this.REFLECTIONMAP_PLANAR = false;
  44518. _this.REFLECTIONMAP_CUBIC = false;
  44519. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44520. _this.REFLECTIONMAP_PROJECTION = false;
  44521. _this.REFLECTIONMAP_SKYBOX = false;
  44522. _this.REFLECTIONMAP_EXPLICIT = false;
  44523. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44524. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44525. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44526. _this.INVERTCUBICMAP = false;
  44527. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44528. _this.USESPHERICALINVERTEX = false;
  44529. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44530. _this.LODINREFLECTIONALPHA = false;
  44531. _this.GAMMAREFLECTION = false;
  44532. _this.RADIANCEOCCLUSION = false;
  44533. _this.HORIZONOCCLUSION = false;
  44534. _this.REFRACTION = false;
  44535. _this.REFRACTIONMAP_3D = false;
  44536. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44537. _this.LODINREFRACTIONALPHA = false;
  44538. _this.GAMMAREFRACTION = false;
  44539. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44540. _this.INSTANCES = false;
  44541. _this.NUM_BONE_INFLUENCERS = 0;
  44542. _this.BonesPerMesh = 0;
  44543. _this.NONUNIFORMSCALING = false;
  44544. _this.MORPHTARGETS = false;
  44545. _this.MORPHTARGETS_NORMAL = false;
  44546. _this.MORPHTARGETS_TANGENT = false;
  44547. _this.NUM_MORPH_INFLUENCERS = 0;
  44548. _this.IMAGEPROCESSING = false;
  44549. _this.VIGNETTE = false;
  44550. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44551. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44552. _this.TONEMAPPING = false;
  44553. _this.CONTRAST = false;
  44554. _this.COLORCURVES = false;
  44555. _this.COLORGRADING = false;
  44556. _this.COLORGRADING3D = false;
  44557. _this.SAMPLER3DGREENDEPTH = false;
  44558. _this.SAMPLER3DBGRMAP = false;
  44559. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44560. _this.EXPOSURE = false;
  44561. _this.USEPHYSICALLIGHTFALLOFF = false;
  44562. _this.TWOSIDEDLIGHTING = false;
  44563. _this.SHADOWFLOAT = false;
  44564. _this.CLIPPLANE = false;
  44565. _this.POINTSIZE = false;
  44566. _this.FOG = false;
  44567. _this.LOGARITHMICDEPTH = false;
  44568. _this.FORCENORMALFORWARD = false;
  44569. _this.SPECULARAA = false;
  44570. _this.UNLIT = false;
  44571. _this.rebuild();
  44572. return _this;
  44573. }
  44574. /**
  44575. * Resets the PBR Material defines.
  44576. */
  44577. PBRMaterialDefines.prototype.reset = function () {
  44578. _super.prototype.reset.call(this);
  44579. this.ALPHATESTVALUE = "0.5";
  44580. this.PBR = true;
  44581. };
  44582. return PBRMaterialDefines;
  44583. }(BABYLON.MaterialDefines));
  44584. /**
  44585. * The Physically based material base class of BJS.
  44586. *
  44587. * This offers the main features of a standard PBR material.
  44588. * For more information, please refer to the documentation :
  44589. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44590. */
  44591. var PBRBaseMaterial = /** @class */ (function (_super) {
  44592. __extends(PBRBaseMaterial, _super);
  44593. /**
  44594. * Instantiates a new PBRMaterial instance.
  44595. *
  44596. * @param name The material name
  44597. * @param scene The scene the material will be use in.
  44598. */
  44599. function PBRBaseMaterial(name, scene) {
  44600. var _this = _super.call(this, name, scene) || this;
  44601. /**
  44602. * Intensity of the direct lights e.g. the four lights available in your scene.
  44603. * This impacts both the direct diffuse and specular highlights.
  44604. */
  44605. _this._directIntensity = 1.0;
  44606. /**
  44607. * Intensity of the emissive part of the material.
  44608. * This helps controlling the emissive effect without modifying the emissive color.
  44609. */
  44610. _this._emissiveIntensity = 1.0;
  44611. /**
  44612. * Intensity of the environment e.g. how much the environment will light the object
  44613. * either through harmonics for rough material or through the refelction for shiny ones.
  44614. */
  44615. _this._environmentIntensity = 1.0;
  44616. /**
  44617. * This is a special control allowing the reduction of the specular highlights coming from the
  44618. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44619. */
  44620. _this._specularIntensity = 1.0;
  44621. /**
  44622. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44623. */
  44624. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44625. /**
  44626. * Debug Control allowing disabling the bump map on this material.
  44627. */
  44628. _this._disableBumpMap = false;
  44629. /**
  44630. * AKA Occlusion Texture Intensity in other nomenclature.
  44631. */
  44632. _this._ambientTextureStrength = 1.0;
  44633. /**
  44634. * The color of a material in ambient lighting.
  44635. */
  44636. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44637. /**
  44638. * AKA Diffuse Color in other nomenclature.
  44639. */
  44640. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44641. /**
  44642. * AKA Specular Color in other nomenclature.
  44643. */
  44644. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44645. /**
  44646. * The color applied when light is reflected from a material.
  44647. */
  44648. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44649. /**
  44650. * The color applied when light is emitted from a material.
  44651. */
  44652. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44653. /**
  44654. * AKA Glossiness in other nomenclature.
  44655. */
  44656. _this._microSurface = 0.9;
  44657. /**
  44658. * source material index of refraction (IOR)' / 'destination material IOR.
  44659. */
  44660. _this._indexOfRefraction = 0.66;
  44661. /**
  44662. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44663. */
  44664. _this._invertRefractionY = false;
  44665. /**
  44666. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44667. * Materials half opaque for instance using refraction could benefit from this control.
  44668. */
  44669. _this._linkRefractionWithTransparency = false;
  44670. /**
  44671. * Specifies that the material will use the light map as a show map.
  44672. */
  44673. _this._useLightmapAsShadowmap = false;
  44674. /**
  44675. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44676. * makes the reflect vector face the model (under horizon).
  44677. */
  44678. _this._useHorizonOcclusion = true;
  44679. /**
  44680. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44681. * too much the area relying on ambient texture to define their ambient occlusion.
  44682. */
  44683. _this._useRadianceOcclusion = true;
  44684. /**
  44685. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44686. */
  44687. _this._useAlphaFromAlbedoTexture = false;
  44688. /**
  44689. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44690. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44691. */
  44692. _this._useSpecularOverAlpha = true;
  44693. /**
  44694. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44695. */
  44696. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44697. /**
  44698. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44699. */
  44700. _this._useRoughnessFromMetallicTextureAlpha = true;
  44701. /**
  44702. * Specifies if the metallic texture contains the roughness information in its green channel.
  44703. */
  44704. _this._useRoughnessFromMetallicTextureGreen = false;
  44705. /**
  44706. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44707. */
  44708. _this._useMetallnessFromMetallicTextureBlue = false;
  44709. /**
  44710. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44711. */
  44712. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44713. /**
  44714. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44715. */
  44716. _this._useAmbientInGrayScale = false;
  44717. /**
  44718. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44719. * The material will try to infer what glossiness each pixel should be.
  44720. */
  44721. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44722. /**
  44723. * BJS is using an harcoded light falloff based on a manually sets up range.
  44724. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44725. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44726. */
  44727. _this._usePhysicalLightFalloff = true;
  44728. /**
  44729. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44730. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44731. */
  44732. _this._useRadianceOverAlpha = true;
  44733. /**
  44734. * Allows using an object space normal map (instead of tangent space).
  44735. */
  44736. _this._useObjectSpaceNormalMap = false;
  44737. /**
  44738. * Allows using the bump map in parallax mode.
  44739. */
  44740. _this._useParallax = false;
  44741. /**
  44742. * Allows using the bump map in parallax occlusion mode.
  44743. */
  44744. _this._useParallaxOcclusion = false;
  44745. /**
  44746. * Controls the scale bias of the parallax mode.
  44747. */
  44748. _this._parallaxScaleBias = 0.05;
  44749. /**
  44750. * If sets to true, disables all the lights affecting the material.
  44751. */
  44752. _this._disableLighting = false;
  44753. /**
  44754. * Number of Simultaneous lights allowed on the material.
  44755. */
  44756. _this._maxSimultaneousLights = 4;
  44757. /**
  44758. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44759. */
  44760. _this._invertNormalMapX = false;
  44761. /**
  44762. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44763. */
  44764. _this._invertNormalMapY = false;
  44765. /**
  44766. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44767. */
  44768. _this._twoSidedLighting = false;
  44769. /**
  44770. * Defines the alpha limits in alpha test mode.
  44771. */
  44772. _this._alphaCutOff = 0.4;
  44773. /**
  44774. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44775. */
  44776. _this._forceAlphaTest = false;
  44777. /**
  44778. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44779. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44780. */
  44781. _this._useAlphaFresnel = false;
  44782. /**
  44783. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44784. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44785. */
  44786. _this._useLinearAlphaFresnel = false;
  44787. /**
  44788. * The transparency mode of the material.
  44789. */
  44790. _this._transparencyMode = null;
  44791. /**
  44792. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44793. * from cos thetav and roughness:
  44794. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44795. */
  44796. _this._environmentBRDFTexture = null;
  44797. /**
  44798. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44799. */
  44800. _this._forceIrradianceInFragment = false;
  44801. /**
  44802. * Force normal to face away from face.
  44803. */
  44804. _this._forceNormalForward = false;
  44805. /**
  44806. * Enables specular anti aliasing in the PBR shader.
  44807. * It will both interacts on the Geometry for analytical and IBL lighting.
  44808. * It also prefilter the roughness map based on the bump values.
  44809. */
  44810. _this._enableSpecularAntiAliasing = false;
  44811. /**
  44812. * Stores the available render targets.
  44813. */
  44814. _this._renderTargets = new BABYLON.SmartArray(16);
  44815. /**
  44816. * Sets the global ambient color for the material used in lighting calculations.
  44817. */
  44818. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44819. /**
  44820. * If set to true, no lighting calculations will be applied.
  44821. */
  44822. _this._unlit = false;
  44823. // Setup the default processing configuration to the scene.
  44824. _this._attachImageProcessingConfiguration(null);
  44825. _this.getRenderTargetTextures = function () {
  44826. _this._renderTargets.reset();
  44827. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44828. _this._renderTargets.push(_this._reflectionTexture);
  44829. }
  44830. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44831. _this._renderTargets.push(_this._refractionTexture);
  44832. }
  44833. return _this._renderTargets;
  44834. };
  44835. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44836. return _this;
  44837. }
  44838. /**
  44839. * Attaches a new image processing configuration to the PBR Material.
  44840. * @param configuration
  44841. */
  44842. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44843. var _this = this;
  44844. if (configuration === this._imageProcessingConfiguration) {
  44845. return;
  44846. }
  44847. // Detaches observer.
  44848. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44849. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44850. }
  44851. // Pick the scene configuration if needed.
  44852. if (!configuration) {
  44853. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44854. }
  44855. else {
  44856. this._imageProcessingConfiguration = configuration;
  44857. }
  44858. // Attaches observer.
  44859. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44860. _this._markAllSubMeshesAsImageProcessingDirty();
  44861. });
  44862. };
  44863. /**
  44864. * Gets the name of the material class.
  44865. */
  44866. PBRBaseMaterial.prototype.getClassName = function () {
  44867. return "PBRBaseMaterial";
  44868. };
  44869. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44870. /**
  44871. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44872. */
  44873. get: function () {
  44874. return this._useLogarithmicDepth;
  44875. },
  44876. /**
  44877. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44878. */
  44879. set: function (value) {
  44880. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44881. },
  44882. enumerable: true,
  44883. configurable: true
  44884. });
  44885. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44886. /**
  44887. * Gets the current transparency mode.
  44888. */
  44889. get: function () {
  44890. return this._transparencyMode;
  44891. },
  44892. /**
  44893. * Sets the transparency mode of the material.
  44894. */
  44895. set: function (value) {
  44896. if (this._transparencyMode === value) {
  44897. return;
  44898. }
  44899. this._transparencyMode = value;
  44900. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44901. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44902. },
  44903. enumerable: true,
  44904. configurable: true
  44905. });
  44906. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44907. /**
  44908. * Returns true if alpha blending should be disabled.
  44909. */
  44910. get: function () {
  44911. return (this._linkRefractionWithTransparency ||
  44912. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44913. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44914. },
  44915. enumerable: true,
  44916. configurable: true
  44917. });
  44918. /**
  44919. * Specifies whether or not this material should be rendered in alpha blend mode.
  44920. */
  44921. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44922. if (this._disableAlphaBlending) {
  44923. return false;
  44924. }
  44925. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44926. };
  44927. /**
  44928. * Specifies if the mesh will require alpha blending.
  44929. * @param mesh - BJS mesh.
  44930. */
  44931. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44932. if (this._disableAlphaBlending) {
  44933. return false;
  44934. }
  44935. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44936. };
  44937. /**
  44938. * Specifies whether or not this material should be rendered in alpha test mode.
  44939. */
  44940. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44941. if (this._forceAlphaTest) {
  44942. return true;
  44943. }
  44944. if (this._linkRefractionWithTransparency) {
  44945. return false;
  44946. }
  44947. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44948. };
  44949. /**
  44950. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44951. */
  44952. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44953. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44954. };
  44955. /**
  44956. * Gets the texture used for the alpha test.
  44957. */
  44958. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44959. return this._albedoTexture;
  44960. };
  44961. /**
  44962. * Specifies that the submesh is ready to be used.
  44963. * @param mesh - BJS mesh.
  44964. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44965. * @param useInstances - Specifies that instances should be used.
  44966. * @returns - boolean indicating that the submesh is ready or not.
  44967. */
  44968. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44969. if (subMesh.effect && this.isFrozen) {
  44970. if (this._wasPreviouslyReady) {
  44971. return true;
  44972. }
  44973. }
  44974. if (!subMesh._materialDefines) {
  44975. subMesh._materialDefines = new PBRMaterialDefines();
  44976. }
  44977. var defines = subMesh._materialDefines;
  44978. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44979. if (defines._renderId === this.getScene().getRenderId()) {
  44980. return true;
  44981. }
  44982. }
  44983. var scene = this.getScene();
  44984. var engine = scene.getEngine();
  44985. if (defines._areTexturesDirty) {
  44986. if (scene.texturesEnabled) {
  44987. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44988. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44989. return false;
  44990. }
  44991. }
  44992. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44993. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44994. return false;
  44995. }
  44996. }
  44997. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44998. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44999. return false;
  45000. }
  45001. }
  45002. var reflectionTexture = this._getReflectionTexture();
  45003. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45004. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45005. return false;
  45006. }
  45007. }
  45008. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45009. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45010. return false;
  45011. }
  45012. }
  45013. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45014. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45015. return false;
  45016. }
  45017. }
  45018. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45019. if (this._metallicTexture) {
  45020. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45021. return false;
  45022. }
  45023. }
  45024. else if (this._reflectivityTexture) {
  45025. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45026. return false;
  45027. }
  45028. }
  45029. if (this._microSurfaceTexture) {
  45030. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45031. return false;
  45032. }
  45033. }
  45034. }
  45035. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45036. // Bump texture cannot be not blocking.
  45037. if (!this._bumpTexture.isReady()) {
  45038. return false;
  45039. }
  45040. }
  45041. var refractionTexture = this._getRefractionTexture();
  45042. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45043. if (!refractionTexture.isReadyOrNotBlocking()) {
  45044. return false;
  45045. }
  45046. }
  45047. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45048. // This is blocking.
  45049. if (!this._environmentBRDFTexture.isReady()) {
  45050. return false;
  45051. }
  45052. }
  45053. }
  45054. }
  45055. if (defines._areImageProcessingDirty) {
  45056. if (!this._imageProcessingConfiguration.isReady()) {
  45057. return false;
  45058. }
  45059. }
  45060. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45061. mesh.createNormals(true);
  45062. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45063. }
  45064. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45065. if (effect) {
  45066. scene.resetCachedMaterial();
  45067. subMesh.setEffect(effect, defines);
  45068. this.buildUniformLayout();
  45069. }
  45070. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45071. return false;
  45072. }
  45073. defines._renderId = scene.getRenderId();
  45074. this._wasPreviouslyReady = true;
  45075. return true;
  45076. };
  45077. /**
  45078. * Specifies if the material uses metallic roughness workflow.
  45079. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45080. */
  45081. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45082. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45083. return true;
  45084. }
  45085. return false;
  45086. };
  45087. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45088. if (onCompiled === void 0) { onCompiled = null; }
  45089. if (onError === void 0) { onError = null; }
  45090. if (useInstances === void 0) { useInstances = null; }
  45091. if (useClipPlane === void 0) { useClipPlane = null; }
  45092. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45093. if (!defines.isDirty) {
  45094. return null;
  45095. }
  45096. defines.markAsProcessed();
  45097. var scene = this.getScene();
  45098. var engine = scene.getEngine();
  45099. // Fallbacks
  45100. var fallbacks = new BABYLON.EffectFallbacks();
  45101. var fallbackRank = 0;
  45102. if (defines.USESPHERICALINVERTEX) {
  45103. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45104. }
  45105. if (defines.FOG) {
  45106. fallbacks.addFallback(fallbackRank, "FOG");
  45107. }
  45108. if (defines.SPECULARAA) {
  45109. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45110. }
  45111. if (defines.POINTSIZE) {
  45112. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45113. }
  45114. if (defines.LOGARITHMICDEPTH) {
  45115. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45116. }
  45117. if (defines.PARALLAX) {
  45118. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45119. }
  45120. if (defines.PARALLAXOCCLUSION) {
  45121. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45122. }
  45123. if (defines.ENVIRONMENTBRDF) {
  45124. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45125. }
  45126. if (defines.TANGENT) {
  45127. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45128. }
  45129. if (defines.BUMP) {
  45130. fallbacks.addFallback(fallbackRank++, "BUMP");
  45131. }
  45132. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45133. if (defines.SPECULARTERM) {
  45134. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45135. }
  45136. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45137. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45138. }
  45139. if (defines.LIGHTMAP) {
  45140. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45141. }
  45142. if (defines.NORMAL) {
  45143. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45144. }
  45145. if (defines.AMBIENT) {
  45146. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45147. }
  45148. if (defines.EMISSIVE) {
  45149. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45150. }
  45151. if (defines.VERTEXCOLOR) {
  45152. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45153. }
  45154. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45155. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45156. }
  45157. if (defines.MORPHTARGETS) {
  45158. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45159. }
  45160. //Attributes
  45161. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45162. if (defines.NORMAL) {
  45163. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45164. }
  45165. if (defines.TANGENT) {
  45166. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45167. }
  45168. if (defines.UV1) {
  45169. attribs.push(BABYLON.VertexBuffer.UVKind);
  45170. }
  45171. if (defines.UV2) {
  45172. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45173. }
  45174. if (defines.VERTEXCOLOR) {
  45175. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45176. }
  45177. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45178. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45179. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45180. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45181. "vFogInfos", "vFogColor", "pointSize",
  45182. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45183. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45184. "mBones",
  45185. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45186. "vLightingIntensity",
  45187. "logarithmicDepthConstant",
  45188. "vSphericalX", "vSphericalY", "vSphericalZ",
  45189. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45190. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45191. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45192. "vTangentSpaceParams"
  45193. ];
  45194. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45195. "bumpSampler", "lightmapSampler", "opacitySampler",
  45196. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45197. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45198. "microSurfaceSampler", "environmentBrdfSampler"];
  45199. var uniformBuffers = ["Material", "Scene"];
  45200. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45201. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45202. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45203. uniformsNames: uniforms,
  45204. uniformBuffersNames: uniformBuffers,
  45205. samplers: samplers,
  45206. defines: defines,
  45207. maxSimultaneousLights: this._maxSimultaneousLights
  45208. });
  45209. var join = defines.toString();
  45210. return engine.createEffect("pbr", {
  45211. attributes: attribs,
  45212. uniformsNames: uniforms,
  45213. uniformBuffersNames: uniformBuffers,
  45214. samplers: samplers,
  45215. defines: join,
  45216. fallbacks: fallbacks,
  45217. onCompiled: onCompiled,
  45218. onError: onError,
  45219. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45220. }, engine);
  45221. };
  45222. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45223. if (useInstances === void 0) { useInstances = null; }
  45224. if (useClipPlane === void 0) { useClipPlane = null; }
  45225. var scene = this.getScene();
  45226. var engine = scene.getEngine();
  45227. // Lights
  45228. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45229. defines._needNormals = true;
  45230. // Textures
  45231. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45232. if (defines._areTexturesDirty) {
  45233. defines._needUVs = false;
  45234. if (scene.texturesEnabled) {
  45235. if (scene.getEngine().getCaps().textureLOD) {
  45236. defines.LODBASEDMICROSFURACE = true;
  45237. }
  45238. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45239. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45240. }
  45241. else {
  45242. defines.ALBEDO = false;
  45243. }
  45244. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45245. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45246. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45247. }
  45248. else {
  45249. defines.AMBIENT = false;
  45250. }
  45251. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45252. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45253. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45254. }
  45255. else {
  45256. defines.OPACITY = false;
  45257. }
  45258. var reflectionTexture = this._getReflectionTexture();
  45259. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45260. defines.REFLECTION = true;
  45261. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45262. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45263. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45264. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45265. defines.INVERTCUBICMAP = true;
  45266. }
  45267. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45268. switch (reflectionTexture.coordinatesMode) {
  45269. case BABYLON.Texture.EXPLICIT_MODE:
  45270. defines.REFLECTIONMAP_EXPLICIT = true;
  45271. break;
  45272. case BABYLON.Texture.PLANAR_MODE:
  45273. defines.REFLECTIONMAP_PLANAR = true;
  45274. break;
  45275. case BABYLON.Texture.PROJECTION_MODE:
  45276. defines.REFLECTIONMAP_PROJECTION = true;
  45277. break;
  45278. case BABYLON.Texture.SKYBOX_MODE:
  45279. defines.REFLECTIONMAP_SKYBOX = true;
  45280. break;
  45281. case BABYLON.Texture.SPHERICAL_MODE:
  45282. defines.REFLECTIONMAP_SPHERICAL = true;
  45283. break;
  45284. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45285. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45286. break;
  45287. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45288. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45289. break;
  45290. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45291. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45292. break;
  45293. case BABYLON.Texture.CUBIC_MODE:
  45294. case BABYLON.Texture.INVCUBIC_MODE:
  45295. default:
  45296. defines.REFLECTIONMAP_CUBIC = true;
  45297. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45298. break;
  45299. }
  45300. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45301. if (reflectionTexture.sphericalPolynomial) {
  45302. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45303. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45304. defines.USESPHERICALINVERTEX = false;
  45305. }
  45306. else {
  45307. defines.USESPHERICALINVERTEX = true;
  45308. }
  45309. }
  45310. }
  45311. }
  45312. else {
  45313. defines.REFLECTION = false;
  45314. defines.REFLECTIONMAP_3D = false;
  45315. defines.REFLECTIONMAP_SPHERICAL = false;
  45316. defines.REFLECTIONMAP_PLANAR = false;
  45317. defines.REFLECTIONMAP_CUBIC = false;
  45318. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45319. defines.REFLECTIONMAP_PROJECTION = false;
  45320. defines.REFLECTIONMAP_SKYBOX = false;
  45321. defines.REFLECTIONMAP_EXPLICIT = false;
  45322. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45323. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45324. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45325. defines.INVERTCUBICMAP = false;
  45326. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45327. defines.USESPHERICALINVERTEX = false;
  45328. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45329. defines.LODINREFLECTIONALPHA = false;
  45330. defines.GAMMAREFLECTION = false;
  45331. }
  45332. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45333. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45334. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45335. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45336. }
  45337. else {
  45338. defines.LIGHTMAP = false;
  45339. }
  45340. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45341. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45342. }
  45343. else {
  45344. defines.EMISSIVE = false;
  45345. }
  45346. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45347. if (this._metallicTexture) {
  45348. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45349. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45350. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45351. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45352. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45353. }
  45354. else if (this._reflectivityTexture) {
  45355. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45356. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45357. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45358. }
  45359. else {
  45360. defines.REFLECTIVITY = false;
  45361. }
  45362. if (this._microSurfaceTexture) {
  45363. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45364. }
  45365. else {
  45366. defines.MICROSURFACEMAP = false;
  45367. }
  45368. }
  45369. else {
  45370. defines.REFLECTIVITY = false;
  45371. defines.MICROSURFACEMAP = false;
  45372. }
  45373. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45374. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45375. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45376. defines.PARALLAX = true;
  45377. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45378. }
  45379. else {
  45380. defines.PARALLAX = false;
  45381. }
  45382. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45383. }
  45384. else {
  45385. defines.BUMP = false;
  45386. }
  45387. var refractionTexture = this._getRefractionTexture();
  45388. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45389. defines.REFRACTION = true;
  45390. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45391. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45392. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45393. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45394. if (this._linkRefractionWithTransparency) {
  45395. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45396. }
  45397. }
  45398. else {
  45399. defines.REFRACTION = false;
  45400. }
  45401. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45402. defines.ENVIRONMENTBRDF = true;
  45403. }
  45404. else {
  45405. defines.ENVIRONMENTBRDF = false;
  45406. }
  45407. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45408. defines.ALPHAFROMALBEDO = true;
  45409. }
  45410. else {
  45411. defines.ALPHAFROMALBEDO = false;
  45412. }
  45413. }
  45414. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45415. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45416. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45417. if (!this.backFaceCulling && this._twoSidedLighting) {
  45418. defines.TWOSIDEDLIGHTING = true;
  45419. }
  45420. else {
  45421. defines.TWOSIDEDLIGHTING = false;
  45422. }
  45423. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45424. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45425. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45426. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45427. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45428. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45429. }
  45430. if (defines._areImageProcessingDirty) {
  45431. this._imageProcessingConfiguration.prepareDefines(defines);
  45432. }
  45433. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45434. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45435. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45436. // Misc.
  45437. if (defines._areMiscDirty) {
  45438. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45439. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45440. }
  45441. // Values that need to be evaluated on every frame
  45442. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45443. // Attribs
  45444. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45445. };
  45446. /**
  45447. * Force shader compilation
  45448. */
  45449. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45450. var _this = this;
  45451. var localOptions = __assign({ clipPlane: false }, options);
  45452. var defines = new PBRMaterialDefines();
  45453. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45454. if (effect.isReady()) {
  45455. if (onCompiled) {
  45456. onCompiled(this);
  45457. }
  45458. }
  45459. else {
  45460. effect.onCompileObservable.add(function () {
  45461. if (onCompiled) {
  45462. onCompiled(_this);
  45463. }
  45464. });
  45465. }
  45466. };
  45467. /**
  45468. * Initializes the uniform buffer layout for the shader.
  45469. */
  45470. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45471. // Order is important !
  45472. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45473. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45474. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45475. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45476. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45477. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45478. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45479. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45480. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45481. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45482. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45483. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45484. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45485. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45486. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45487. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45488. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45489. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45490. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45491. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45492. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45493. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45494. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45495. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45496. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45497. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45498. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45499. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45500. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45501. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45502. this._uniformBuffer.addUniform("pointSize", 1);
  45503. this._uniformBuffer.create();
  45504. };
  45505. /**
  45506. * Unbinds the textures.
  45507. */
  45508. PBRBaseMaterial.prototype.unbind = function () {
  45509. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45510. this._uniformBuffer.setTexture("reflectionSampler", null);
  45511. }
  45512. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45513. this._uniformBuffer.setTexture("refractionSampler", null);
  45514. }
  45515. _super.prototype.unbind.call(this);
  45516. };
  45517. /**
  45518. * Binds the submesh data.
  45519. * @param world - The world matrix.
  45520. * @param mesh - The BJS mesh.
  45521. * @param subMesh - A submesh of the BJS mesh.
  45522. */
  45523. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45524. var scene = this.getScene();
  45525. var defines = subMesh._materialDefines;
  45526. if (!defines) {
  45527. return;
  45528. }
  45529. var effect = subMesh.effect;
  45530. if (!effect) {
  45531. return;
  45532. }
  45533. this._activeEffect = effect;
  45534. // Matrices
  45535. this.bindOnlyWorldMatrix(world);
  45536. // Normal Matrix
  45537. if (defines.OBJECTSPACE_NORMALMAP) {
  45538. world.toNormalMatrix(this._normalMatrix);
  45539. this.bindOnlyNormalMatrix(this._normalMatrix);
  45540. }
  45541. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45542. // Bones
  45543. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45544. var reflectionTexture = null;
  45545. if (mustRebind) {
  45546. this._uniformBuffer.bindToEffect(effect, "Material");
  45547. this.bindViewProjection(effect);
  45548. reflectionTexture = this._getReflectionTexture();
  45549. var refractionTexture = this._getRefractionTexture();
  45550. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45551. // Texture uniforms
  45552. if (scene.texturesEnabled) {
  45553. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45554. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45555. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45556. }
  45557. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45558. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45559. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45560. }
  45561. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45562. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45563. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45564. }
  45565. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45566. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45567. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45568. if (reflectionTexture.boundingBoxSize) {
  45569. var cubeTexture = reflectionTexture;
  45570. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45571. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45572. }
  45573. var polynomials = reflectionTexture.sphericalPolynomial;
  45574. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45575. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45576. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45577. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45578. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45579. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45580. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45581. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45582. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45583. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45584. }
  45585. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45586. }
  45587. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45588. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45589. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45590. }
  45591. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45592. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45593. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45594. }
  45595. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45596. if (this._metallicTexture) {
  45597. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45598. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45599. }
  45600. else if (this._reflectivityTexture) {
  45601. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45602. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45603. }
  45604. if (this._microSurfaceTexture) {
  45605. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45606. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45607. }
  45608. }
  45609. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45610. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45611. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45612. if (scene._mirroredCameraPosition) {
  45613. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45614. }
  45615. else {
  45616. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45617. }
  45618. }
  45619. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45620. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45621. var depth = 1.0;
  45622. if (!refractionTexture.isCube) {
  45623. if (refractionTexture.depth) {
  45624. depth = refractionTexture.depth;
  45625. }
  45626. }
  45627. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45628. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45629. }
  45630. }
  45631. // Point size
  45632. if (this.pointsCloud) {
  45633. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45634. }
  45635. // Colors
  45636. if (defines.METALLICWORKFLOW) {
  45637. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45638. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45639. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45640. }
  45641. else {
  45642. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45643. }
  45644. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45645. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45646. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45647. // Misc
  45648. this._lightingInfos.x = this._directIntensity;
  45649. this._lightingInfos.y = this._emissiveIntensity;
  45650. this._lightingInfos.z = this._environmentIntensity;
  45651. this._lightingInfos.w = this._specularIntensity;
  45652. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45653. }
  45654. // Textures
  45655. if (scene.texturesEnabled) {
  45656. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45657. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45658. }
  45659. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45660. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45661. }
  45662. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45663. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45664. }
  45665. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45666. if (defines.LODBASEDMICROSFURACE) {
  45667. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45668. }
  45669. else {
  45670. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45671. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45672. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45673. }
  45674. }
  45675. if (defines.ENVIRONMENTBRDF) {
  45676. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45677. }
  45678. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45679. if (defines.LODBASEDMICROSFURACE) {
  45680. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45681. }
  45682. else {
  45683. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45684. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45685. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45686. }
  45687. }
  45688. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45689. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45690. }
  45691. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45692. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45693. }
  45694. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45695. if (this._metallicTexture) {
  45696. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45697. }
  45698. else if (this._reflectivityTexture) {
  45699. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45700. }
  45701. if (this._microSurfaceTexture) {
  45702. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45703. }
  45704. }
  45705. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45706. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45707. }
  45708. }
  45709. // Clip plane
  45710. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45711. // Colors
  45712. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45713. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45714. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45715. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45716. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45717. }
  45718. if (mustRebind || !this.isFrozen) {
  45719. // Lights
  45720. if (scene.lightsEnabled && !this._disableLighting) {
  45721. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45722. }
  45723. // View
  45724. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45725. this.bindView(effect);
  45726. }
  45727. // Fog
  45728. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45729. // Morph targets
  45730. if (defines.NUM_MORPH_INFLUENCERS) {
  45731. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45732. }
  45733. // image processing
  45734. this._imageProcessingConfiguration.bind(this._activeEffect);
  45735. // Log. depth
  45736. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45737. }
  45738. this._uniformBuffer.update();
  45739. this._afterBind(mesh, this._activeEffect);
  45740. };
  45741. /**
  45742. * Returns the animatable textures.
  45743. * @returns - Array of animatable textures.
  45744. */
  45745. PBRBaseMaterial.prototype.getAnimatables = function () {
  45746. var results = [];
  45747. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45748. results.push(this._albedoTexture);
  45749. }
  45750. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45751. results.push(this._ambientTexture);
  45752. }
  45753. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45754. results.push(this._opacityTexture);
  45755. }
  45756. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45757. results.push(this._reflectionTexture);
  45758. }
  45759. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45760. results.push(this._emissiveTexture);
  45761. }
  45762. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45763. results.push(this._metallicTexture);
  45764. }
  45765. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45766. results.push(this._reflectivityTexture);
  45767. }
  45768. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45769. results.push(this._bumpTexture);
  45770. }
  45771. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45772. results.push(this._lightmapTexture);
  45773. }
  45774. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45775. results.push(this._refractionTexture);
  45776. }
  45777. return results;
  45778. };
  45779. /**
  45780. * Returns the texture used for reflections.
  45781. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45782. */
  45783. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45784. if (this._reflectionTexture) {
  45785. return this._reflectionTexture;
  45786. }
  45787. return this.getScene().environmentTexture;
  45788. };
  45789. /**
  45790. * Returns the texture used for refraction or null if none is used.
  45791. * @returns - Refection texture if present. If no refraction texture and refraction
  45792. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45793. */
  45794. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45795. if (this._refractionTexture) {
  45796. return this._refractionTexture;
  45797. }
  45798. if (this._linkRefractionWithTransparency) {
  45799. return this.getScene().environmentTexture;
  45800. }
  45801. return null;
  45802. };
  45803. /**
  45804. * Disposes the resources of the material.
  45805. * @param forceDisposeEffect - Forces the disposal of effects.
  45806. * @param forceDisposeTextures - Forces the disposal of all textures.
  45807. */
  45808. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45809. if (forceDisposeTextures) {
  45810. if (this._albedoTexture) {
  45811. this._albedoTexture.dispose();
  45812. }
  45813. if (this._ambientTexture) {
  45814. this._ambientTexture.dispose();
  45815. }
  45816. if (this._opacityTexture) {
  45817. this._opacityTexture.dispose();
  45818. }
  45819. if (this._reflectionTexture) {
  45820. this._reflectionTexture.dispose();
  45821. }
  45822. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45823. this._environmentBRDFTexture.dispose();
  45824. }
  45825. if (this._emissiveTexture) {
  45826. this._emissiveTexture.dispose();
  45827. }
  45828. if (this._metallicTexture) {
  45829. this._metallicTexture.dispose();
  45830. }
  45831. if (this._reflectivityTexture) {
  45832. this._reflectivityTexture.dispose();
  45833. }
  45834. if (this._bumpTexture) {
  45835. this._bumpTexture.dispose();
  45836. }
  45837. if (this._lightmapTexture) {
  45838. this._lightmapTexture.dispose();
  45839. }
  45840. if (this._refractionTexture) {
  45841. this._refractionTexture.dispose();
  45842. }
  45843. }
  45844. this._renderTargets.dispose();
  45845. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45846. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45847. }
  45848. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45849. };
  45850. /**
  45851. * Stores the reflectivity values based on metallic roughness workflow.
  45852. */
  45853. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45854. __decorate([
  45855. BABYLON.serializeAsImageProcessingConfiguration()
  45856. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45857. __decorate([
  45858. BABYLON.serialize()
  45859. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45860. __decorate([
  45861. BABYLON.serialize()
  45862. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45863. return PBRBaseMaterial;
  45864. }(BABYLON.PushMaterial));
  45865. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45866. })(BABYLON || (BABYLON = {}));
  45867. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45868. var BABYLON;
  45869. (function (BABYLON) {
  45870. /**
  45871. * The Physically based simple base material of BJS.
  45872. *
  45873. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45874. * It is used as the base class for both the specGloss and metalRough conventions.
  45875. */
  45876. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45877. __extends(PBRBaseSimpleMaterial, _super);
  45878. /**
  45879. * Instantiates a new PBRMaterial instance.
  45880. *
  45881. * @param name The material name
  45882. * @param scene The scene the material will be use in.
  45883. */
  45884. function PBRBaseSimpleMaterial(name, scene) {
  45885. var _this = _super.call(this, name, scene) || this;
  45886. /**
  45887. * Number of Simultaneous lights allowed on the material.
  45888. */
  45889. _this.maxSimultaneousLights = 4;
  45890. /**
  45891. * If sets to true, disables all the lights affecting the material.
  45892. */
  45893. _this.disableLighting = false;
  45894. /**
  45895. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45896. */
  45897. _this.invertNormalMapX = false;
  45898. /**
  45899. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45900. */
  45901. _this.invertNormalMapY = false;
  45902. /**
  45903. * Emissivie color used to self-illuminate the model.
  45904. */
  45905. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45906. /**
  45907. * Occlusion Channel Strenght.
  45908. */
  45909. _this.occlusionStrength = 1.0;
  45910. _this.useLightmapAsShadowmap = false;
  45911. _this._useAlphaFromAlbedoTexture = true;
  45912. _this._useAmbientInGrayScale = true;
  45913. return _this;
  45914. }
  45915. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45916. /**
  45917. * Gets the current double sided mode.
  45918. */
  45919. get: function () {
  45920. return this._twoSidedLighting;
  45921. },
  45922. /**
  45923. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45924. */
  45925. set: function (value) {
  45926. if (this._twoSidedLighting === value) {
  45927. return;
  45928. }
  45929. this._twoSidedLighting = value;
  45930. this.backFaceCulling = !value;
  45931. this._markAllSubMeshesAsTexturesDirty();
  45932. },
  45933. enumerable: true,
  45934. configurable: true
  45935. });
  45936. /**
  45937. * Return the active textures of the material.
  45938. */
  45939. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45940. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45941. if (this.environmentTexture) {
  45942. activeTextures.push(this.environmentTexture);
  45943. }
  45944. if (this.normalTexture) {
  45945. activeTextures.push(this.normalTexture);
  45946. }
  45947. if (this.emissiveTexture) {
  45948. activeTextures.push(this.emissiveTexture);
  45949. }
  45950. if (this.occlusionTexture) {
  45951. activeTextures.push(this.occlusionTexture);
  45952. }
  45953. if (this.lightmapTexture) {
  45954. activeTextures.push(this.lightmapTexture);
  45955. }
  45956. return activeTextures;
  45957. };
  45958. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45959. if (_super.prototype.hasTexture.call(this, texture)) {
  45960. return true;
  45961. }
  45962. if (this.lightmapTexture === texture) {
  45963. return true;
  45964. }
  45965. return false;
  45966. };
  45967. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45968. return "PBRBaseSimpleMaterial";
  45969. };
  45970. __decorate([
  45971. BABYLON.serialize(),
  45972. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45973. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45974. __decorate([
  45975. BABYLON.serialize(),
  45976. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45977. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45978. __decorate([
  45979. BABYLON.serializeAsTexture(),
  45980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45981. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45982. __decorate([
  45983. BABYLON.serialize(),
  45984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45985. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45986. __decorate([
  45987. BABYLON.serialize(),
  45988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45989. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45990. __decorate([
  45991. BABYLON.serializeAsTexture(),
  45992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45993. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45994. __decorate([
  45995. BABYLON.serializeAsColor3("emissive"),
  45996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45997. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45998. __decorate([
  45999. BABYLON.serializeAsTexture(),
  46000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46001. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46002. __decorate([
  46003. BABYLON.serialize(),
  46004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46005. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46006. __decorate([
  46007. BABYLON.serializeAsTexture(),
  46008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46009. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46010. __decorate([
  46011. BABYLON.serialize(),
  46012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46013. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46014. __decorate([
  46015. BABYLON.serialize()
  46016. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46017. __decorate([
  46018. BABYLON.serializeAsTexture(),
  46019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46020. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46021. __decorate([
  46022. BABYLON.serialize(),
  46023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46024. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46025. return PBRBaseSimpleMaterial;
  46026. }(BABYLON.PBRBaseMaterial));
  46027. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46028. })(BABYLON || (BABYLON = {}));
  46029. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46030. var BABYLON;
  46031. (function (BABYLON) {
  46032. /**
  46033. * The Physically based material of BJS.
  46034. *
  46035. * This offers the main features of a standard PBR material.
  46036. * For more information, please refer to the documentation :
  46037. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46038. */
  46039. var PBRMaterial = /** @class */ (function (_super) {
  46040. __extends(PBRMaterial, _super);
  46041. /**
  46042. * Instantiates a new PBRMaterial instance.
  46043. *
  46044. * @param name The material name
  46045. * @param scene The scene the material will be use in.
  46046. */
  46047. function PBRMaterial(name, scene) {
  46048. var _this = _super.call(this, name, scene) || this;
  46049. /**
  46050. * Intensity of the direct lights e.g. the four lights available in your scene.
  46051. * This impacts both the direct diffuse and specular highlights.
  46052. */
  46053. _this.directIntensity = 1.0;
  46054. /**
  46055. * Intensity of the emissive part of the material.
  46056. * This helps controlling the emissive effect without modifying the emissive color.
  46057. */
  46058. _this.emissiveIntensity = 1.0;
  46059. /**
  46060. * Intensity of the environment e.g. how much the environment will light the object
  46061. * either through harmonics for rough material or through the refelction for shiny ones.
  46062. */
  46063. _this.environmentIntensity = 1.0;
  46064. /**
  46065. * This is a special control allowing the reduction of the specular highlights coming from the
  46066. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46067. */
  46068. _this.specularIntensity = 1.0;
  46069. /**
  46070. * Debug Control allowing disabling the bump map on this material.
  46071. */
  46072. _this.disableBumpMap = false;
  46073. /**
  46074. * AKA Occlusion Texture Intensity in other nomenclature.
  46075. */
  46076. _this.ambientTextureStrength = 1.0;
  46077. /**
  46078. * The color of a material in ambient lighting.
  46079. */
  46080. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46081. /**
  46082. * AKA Diffuse Color in other nomenclature.
  46083. */
  46084. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46085. /**
  46086. * AKA Specular Color in other nomenclature.
  46087. */
  46088. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46089. /**
  46090. * The color reflected from the material.
  46091. */
  46092. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46093. /**
  46094. * The color emitted from the material.
  46095. */
  46096. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46097. /**
  46098. * AKA Glossiness in other nomenclature.
  46099. */
  46100. _this.microSurface = 1.0;
  46101. /**
  46102. * source material index of refraction (IOR)' / 'destination material IOR.
  46103. */
  46104. _this.indexOfRefraction = 0.66;
  46105. /**
  46106. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46107. */
  46108. _this.invertRefractionY = false;
  46109. /**
  46110. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46111. * Materials half opaque for instance using refraction could benefit from this control.
  46112. */
  46113. _this.linkRefractionWithTransparency = false;
  46114. _this.useLightmapAsShadowmap = false;
  46115. /**
  46116. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46117. */
  46118. _this.useAlphaFromAlbedoTexture = false;
  46119. /**
  46120. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46121. */
  46122. _this.forceAlphaTest = false;
  46123. /**
  46124. * Defines the alpha limits in alpha test mode.
  46125. */
  46126. _this.alphaCutOff = 0.4;
  46127. /**
  46128. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46129. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46130. */
  46131. _this.useSpecularOverAlpha = true;
  46132. /**
  46133. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46134. */
  46135. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46136. /**
  46137. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46138. */
  46139. _this.useRoughnessFromMetallicTextureAlpha = true;
  46140. /**
  46141. * Specifies if the metallic texture contains the roughness information in its green channel.
  46142. */
  46143. _this.useRoughnessFromMetallicTextureGreen = false;
  46144. /**
  46145. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46146. */
  46147. _this.useMetallnessFromMetallicTextureBlue = false;
  46148. /**
  46149. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46150. */
  46151. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46152. /**
  46153. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46154. */
  46155. _this.useAmbientInGrayScale = false;
  46156. /**
  46157. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46158. * The material will try to infer what glossiness each pixel should be.
  46159. */
  46160. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46161. /**
  46162. * BJS is using an harcoded light falloff based on a manually sets up range.
  46163. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46164. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46165. */
  46166. _this.usePhysicalLightFalloff = true;
  46167. /**
  46168. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46169. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46170. */
  46171. _this.useRadianceOverAlpha = true;
  46172. /**
  46173. * Allows using an object space normal map (instead of tangent space).
  46174. */
  46175. _this.useObjectSpaceNormalMap = false;
  46176. /**
  46177. * Allows using the bump map in parallax mode.
  46178. */
  46179. _this.useParallax = false;
  46180. /**
  46181. * Allows using the bump map in parallax occlusion mode.
  46182. */
  46183. _this.useParallaxOcclusion = false;
  46184. /**
  46185. * Controls the scale bias of the parallax mode.
  46186. */
  46187. _this.parallaxScaleBias = 0.05;
  46188. /**
  46189. * If sets to true, disables all the lights affecting the material.
  46190. */
  46191. _this.disableLighting = false;
  46192. /**
  46193. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46194. */
  46195. _this.forceIrradianceInFragment = false;
  46196. /**
  46197. * Number of Simultaneous lights allowed on the material.
  46198. */
  46199. _this.maxSimultaneousLights = 4;
  46200. /**
  46201. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46202. */
  46203. _this.invertNormalMapX = false;
  46204. /**
  46205. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46206. */
  46207. _this.invertNormalMapY = false;
  46208. /**
  46209. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46210. */
  46211. _this.twoSidedLighting = false;
  46212. /**
  46213. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46214. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46215. */
  46216. _this.useAlphaFresnel = false;
  46217. /**
  46218. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46219. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46220. */
  46221. _this.useLinearAlphaFresnel = false;
  46222. /**
  46223. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46224. * And/Or occlude the blended part.
  46225. */
  46226. _this.environmentBRDFTexture = null;
  46227. /**
  46228. * Force normal to face away from face.
  46229. */
  46230. _this.forceNormalForward = false;
  46231. /**
  46232. * Enables specular anti aliasing in the PBR shader.
  46233. * It will both interacts on the Geometry for analytical and IBL lighting.
  46234. * It also prefilter the roughness map based on the bump values.
  46235. */
  46236. _this.enableSpecularAntiAliasing = false;
  46237. /**
  46238. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46239. * makes the reflect vector face the model (under horizon).
  46240. */
  46241. _this.useHorizonOcclusion = true;
  46242. /**
  46243. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46244. * too much the area relying on ambient texture to define their ambient occlusion.
  46245. */
  46246. _this.useRadianceOcclusion = true;
  46247. /**
  46248. * If set to true, no lighting calculations will be applied.
  46249. */
  46250. _this.unlit = false;
  46251. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46252. return _this;
  46253. }
  46254. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46255. /**
  46256. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46257. */
  46258. get: function () {
  46259. return this._PBRMATERIAL_OPAQUE;
  46260. },
  46261. enumerable: true,
  46262. configurable: true
  46263. });
  46264. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46265. /**
  46266. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46267. */
  46268. get: function () {
  46269. return this._PBRMATERIAL_ALPHATEST;
  46270. },
  46271. enumerable: true,
  46272. configurable: true
  46273. });
  46274. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46275. /**
  46276. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46277. */
  46278. get: function () {
  46279. return this._PBRMATERIAL_ALPHABLEND;
  46280. },
  46281. enumerable: true,
  46282. configurable: true
  46283. });
  46284. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46285. /**
  46286. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46287. * They are also discarded below the alpha cutoff threshold to improve performances.
  46288. */
  46289. get: function () {
  46290. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46291. },
  46292. enumerable: true,
  46293. configurable: true
  46294. });
  46295. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46296. /**
  46297. * Gets the image processing configuration used either in this material.
  46298. */
  46299. get: function () {
  46300. return this._imageProcessingConfiguration;
  46301. },
  46302. /**
  46303. * Sets the Default image processing configuration used either in the this material.
  46304. *
  46305. * If sets to null, the scene one is in use.
  46306. */
  46307. set: function (value) {
  46308. this._attachImageProcessingConfiguration(value);
  46309. // Ensure the effect will be rebuilt.
  46310. this._markAllSubMeshesAsTexturesDirty();
  46311. },
  46312. enumerable: true,
  46313. configurable: true
  46314. });
  46315. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46316. /**
  46317. * Gets wether the color curves effect is enabled.
  46318. */
  46319. get: function () {
  46320. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46321. },
  46322. /**
  46323. * Sets wether the color curves effect is enabled.
  46324. */
  46325. set: function (value) {
  46326. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46327. },
  46328. enumerable: true,
  46329. configurable: true
  46330. });
  46331. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46332. /**
  46333. * Gets wether the color grading effect is enabled.
  46334. */
  46335. get: function () {
  46336. return this.imageProcessingConfiguration.colorGradingEnabled;
  46337. },
  46338. /**
  46339. * Gets wether the color grading effect is enabled.
  46340. */
  46341. set: function (value) {
  46342. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46343. },
  46344. enumerable: true,
  46345. configurable: true
  46346. });
  46347. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46348. /**
  46349. * Gets wether tonemapping is enabled or not.
  46350. */
  46351. get: function () {
  46352. return this._imageProcessingConfiguration.toneMappingEnabled;
  46353. },
  46354. /**
  46355. * Sets wether tonemapping is enabled or not
  46356. */
  46357. set: function (value) {
  46358. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46359. },
  46360. enumerable: true,
  46361. configurable: true
  46362. });
  46363. ;
  46364. ;
  46365. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46366. /**
  46367. * The camera exposure used on this material.
  46368. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46369. * This corresponds to a photographic exposure.
  46370. */
  46371. get: function () {
  46372. return this._imageProcessingConfiguration.exposure;
  46373. },
  46374. /**
  46375. * The camera exposure used on this material.
  46376. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46377. * This corresponds to a photographic exposure.
  46378. */
  46379. set: function (value) {
  46380. this._imageProcessingConfiguration.exposure = value;
  46381. },
  46382. enumerable: true,
  46383. configurable: true
  46384. });
  46385. ;
  46386. ;
  46387. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46388. /**
  46389. * Gets The camera contrast used on this material.
  46390. */
  46391. get: function () {
  46392. return this._imageProcessingConfiguration.contrast;
  46393. },
  46394. /**
  46395. * Sets The camera contrast used on this material.
  46396. */
  46397. set: function (value) {
  46398. this._imageProcessingConfiguration.contrast = value;
  46399. },
  46400. enumerable: true,
  46401. configurable: true
  46402. });
  46403. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46404. /**
  46405. * Gets the Color Grading 2D Lookup Texture.
  46406. */
  46407. get: function () {
  46408. return this._imageProcessingConfiguration.colorGradingTexture;
  46409. },
  46410. /**
  46411. * Sets the Color Grading 2D Lookup Texture.
  46412. */
  46413. set: function (value) {
  46414. this._imageProcessingConfiguration.colorGradingTexture = value;
  46415. },
  46416. enumerable: true,
  46417. configurable: true
  46418. });
  46419. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46420. /**
  46421. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46422. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46423. * 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;
  46424. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46425. */
  46426. get: function () {
  46427. return this._imageProcessingConfiguration.colorCurves;
  46428. },
  46429. /**
  46430. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46431. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46432. * 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;
  46433. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46434. */
  46435. set: function (value) {
  46436. this._imageProcessingConfiguration.colorCurves = value;
  46437. },
  46438. enumerable: true,
  46439. configurable: true
  46440. });
  46441. /**
  46442. * Returns the name of this material class.
  46443. */
  46444. PBRMaterial.prototype.getClassName = function () {
  46445. return "PBRMaterial";
  46446. };
  46447. /**
  46448. * Returns an array of the actively used textures.
  46449. * @returns - Array of BaseTextures
  46450. */
  46451. PBRMaterial.prototype.getActiveTextures = function () {
  46452. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46453. if (this._albedoTexture) {
  46454. activeTextures.push(this._albedoTexture);
  46455. }
  46456. if (this._ambientTexture) {
  46457. activeTextures.push(this._ambientTexture);
  46458. }
  46459. if (this._opacityTexture) {
  46460. activeTextures.push(this._opacityTexture);
  46461. }
  46462. if (this._reflectionTexture) {
  46463. activeTextures.push(this._reflectionTexture);
  46464. }
  46465. if (this._emissiveTexture) {
  46466. activeTextures.push(this._emissiveTexture);
  46467. }
  46468. if (this._reflectivityTexture) {
  46469. activeTextures.push(this._reflectivityTexture);
  46470. }
  46471. if (this._metallicTexture) {
  46472. activeTextures.push(this._metallicTexture);
  46473. }
  46474. if (this._microSurfaceTexture) {
  46475. activeTextures.push(this._microSurfaceTexture);
  46476. }
  46477. if (this._bumpTexture) {
  46478. activeTextures.push(this._bumpTexture);
  46479. }
  46480. if (this._lightmapTexture) {
  46481. activeTextures.push(this._lightmapTexture);
  46482. }
  46483. if (this._refractionTexture) {
  46484. activeTextures.push(this._refractionTexture);
  46485. }
  46486. return activeTextures;
  46487. };
  46488. /**
  46489. * Checks to see if a texture is used in the material.
  46490. * @param texture - Base texture to use.
  46491. * @returns - Boolean specifying if a texture is used in the material.
  46492. */
  46493. PBRMaterial.prototype.hasTexture = function (texture) {
  46494. if (_super.prototype.hasTexture.call(this, texture)) {
  46495. return true;
  46496. }
  46497. if (this._albedoTexture === texture) {
  46498. return true;
  46499. }
  46500. if (this._ambientTexture === texture) {
  46501. return true;
  46502. }
  46503. if (this._opacityTexture === texture) {
  46504. return true;
  46505. }
  46506. if (this._reflectionTexture === texture) {
  46507. return true;
  46508. }
  46509. if (this._reflectivityTexture === texture) {
  46510. return true;
  46511. }
  46512. if (this._metallicTexture === texture) {
  46513. return true;
  46514. }
  46515. if (this._microSurfaceTexture === texture) {
  46516. return true;
  46517. }
  46518. if (this._bumpTexture === texture) {
  46519. return true;
  46520. }
  46521. if (this._lightmapTexture === texture) {
  46522. return true;
  46523. }
  46524. if (this._refractionTexture === texture) {
  46525. return true;
  46526. }
  46527. return false;
  46528. };
  46529. /**
  46530. * Makes a duplicate of the current material.
  46531. * @param name - name to use for the new material.
  46532. */
  46533. PBRMaterial.prototype.clone = function (name) {
  46534. var _this = this;
  46535. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46536. clone.id = name;
  46537. clone.name = name;
  46538. return clone;
  46539. };
  46540. /**
  46541. * Serializes this PBR Material.
  46542. * @returns - An object with the serialized material.
  46543. */
  46544. PBRMaterial.prototype.serialize = function () {
  46545. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46546. serializationObject.customType = "BABYLON.PBRMaterial";
  46547. return serializationObject;
  46548. };
  46549. // Statics
  46550. /**
  46551. * Parses a PBR Material from a serialized object.
  46552. * @param source - Serialized object.
  46553. * @param scene - BJS scene instance.
  46554. * @param rootUrl - url for the scene object
  46555. * @returns - PBRMaterial
  46556. */
  46557. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46558. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46559. };
  46560. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46561. /**
  46562. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46563. */
  46564. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46565. /**
  46566. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46567. */
  46568. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46569. /**
  46570. * 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.
  46571. * They are also discarded below the alpha cutoff threshold to improve performances.
  46572. */
  46573. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46574. __decorate([
  46575. BABYLON.serialize(),
  46576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46577. ], PBRMaterial.prototype, "directIntensity", void 0);
  46578. __decorate([
  46579. BABYLON.serialize(),
  46580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46581. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46582. __decorate([
  46583. BABYLON.serialize(),
  46584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46585. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46586. __decorate([
  46587. BABYLON.serialize(),
  46588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46589. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46590. __decorate([
  46591. BABYLON.serialize(),
  46592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46593. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46594. __decorate([
  46595. BABYLON.serializeAsTexture(),
  46596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46597. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46598. __decorate([
  46599. BABYLON.serializeAsTexture(),
  46600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46601. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46602. __decorate([
  46603. BABYLON.serialize(),
  46604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46605. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46606. __decorate([
  46607. BABYLON.serializeAsTexture(),
  46608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46609. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46610. __decorate([
  46611. BABYLON.serializeAsTexture(),
  46612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46613. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46614. __decorate([
  46615. BABYLON.serializeAsTexture(),
  46616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46617. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46618. __decorate([
  46619. BABYLON.serializeAsTexture(),
  46620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46621. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46622. __decorate([
  46623. BABYLON.serializeAsTexture(),
  46624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46625. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46626. __decorate([
  46627. BABYLON.serialize(),
  46628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46629. ], PBRMaterial.prototype, "metallic", void 0);
  46630. __decorate([
  46631. BABYLON.serialize(),
  46632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46633. ], PBRMaterial.prototype, "roughness", void 0);
  46634. __decorate([
  46635. BABYLON.serializeAsTexture(),
  46636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46637. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46638. __decorate([
  46639. BABYLON.serializeAsTexture(),
  46640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46641. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46642. __decorate([
  46643. BABYLON.serializeAsTexture(),
  46644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46645. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46646. __decorate([
  46647. BABYLON.serializeAsTexture(),
  46648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46649. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46650. __decorate([
  46651. BABYLON.serializeAsColor3("ambient"),
  46652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46653. ], PBRMaterial.prototype, "ambientColor", void 0);
  46654. __decorate([
  46655. BABYLON.serializeAsColor3("albedo"),
  46656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46657. ], PBRMaterial.prototype, "albedoColor", void 0);
  46658. __decorate([
  46659. BABYLON.serializeAsColor3("reflectivity"),
  46660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46661. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46662. __decorate([
  46663. BABYLON.serializeAsColor3("reflection"),
  46664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46665. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46666. __decorate([
  46667. BABYLON.serializeAsColor3("emissive"),
  46668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46669. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46670. __decorate([
  46671. BABYLON.serialize(),
  46672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46673. ], PBRMaterial.prototype, "microSurface", void 0);
  46674. __decorate([
  46675. BABYLON.serialize(),
  46676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46677. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46678. __decorate([
  46679. BABYLON.serialize(),
  46680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46681. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46682. __decorate([
  46683. BABYLON.serialize(),
  46684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46685. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46686. __decorate([
  46687. BABYLON.serialize(),
  46688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46689. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46690. __decorate([
  46691. BABYLON.serialize(),
  46692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46693. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46694. __decorate([
  46695. BABYLON.serialize(),
  46696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46697. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46698. __decorate([
  46699. BABYLON.serialize(),
  46700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46701. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46702. __decorate([
  46703. BABYLON.serialize(),
  46704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46705. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46706. __decorate([
  46707. BABYLON.serialize(),
  46708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46709. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46710. __decorate([
  46711. BABYLON.serialize(),
  46712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46713. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46714. __decorate([
  46715. BABYLON.serialize(),
  46716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46717. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46718. __decorate([
  46719. BABYLON.serialize(),
  46720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46721. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46722. __decorate([
  46723. BABYLON.serialize(),
  46724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46725. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46726. __decorate([
  46727. BABYLON.serialize(),
  46728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46729. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46730. __decorate([
  46731. BABYLON.serialize(),
  46732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46733. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46734. __decorate([
  46735. BABYLON.serialize(),
  46736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46737. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46738. __decorate([
  46739. BABYLON.serialize(),
  46740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46741. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46742. __decorate([
  46743. BABYLON.serialize(),
  46744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46745. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46746. __decorate([
  46747. BABYLON.serialize(),
  46748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46749. ], PBRMaterial.prototype, "useParallax", void 0);
  46750. __decorate([
  46751. BABYLON.serialize(),
  46752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46753. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46754. __decorate([
  46755. BABYLON.serialize(),
  46756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46757. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46758. __decorate([
  46759. BABYLON.serialize(),
  46760. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46761. ], PBRMaterial.prototype, "disableLighting", void 0);
  46762. __decorate([
  46763. BABYLON.serialize(),
  46764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46765. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46766. __decorate([
  46767. BABYLON.serialize(),
  46768. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46769. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46770. __decorate([
  46771. BABYLON.serialize(),
  46772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46773. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46774. __decorate([
  46775. BABYLON.serialize(),
  46776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46777. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46778. __decorate([
  46779. BABYLON.serialize(),
  46780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46781. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46782. __decorate([
  46783. BABYLON.serialize(),
  46784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46785. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46786. __decorate([
  46787. BABYLON.serialize(),
  46788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46789. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46790. __decorate([
  46791. BABYLON.serializeAsTexture(),
  46792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46793. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46794. __decorate([
  46795. BABYLON.serialize(),
  46796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46797. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46798. __decorate([
  46799. BABYLON.serialize(),
  46800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46801. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46802. __decorate([
  46803. BABYLON.serialize(),
  46804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46805. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46806. __decorate([
  46807. BABYLON.serialize(),
  46808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46809. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46810. __decorate([
  46811. BABYLON.serialize(),
  46812. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46813. ], PBRMaterial.prototype, "unlit", void 0);
  46814. return PBRMaterial;
  46815. }(BABYLON.PBRBaseMaterial));
  46816. BABYLON.PBRMaterial = PBRMaterial;
  46817. })(BABYLON || (BABYLON = {}));
  46818. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46819. var BABYLON;
  46820. (function (BABYLON) {
  46821. /**
  46822. * The PBR material of BJS following the metal roughness convention.
  46823. *
  46824. * This fits to the PBR convention in the GLTF definition:
  46825. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46826. */
  46827. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46828. __extends(PBRMetallicRoughnessMaterial, _super);
  46829. /**
  46830. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46831. *
  46832. * @param name The material name
  46833. * @param scene The scene the material will be use in.
  46834. */
  46835. function PBRMetallicRoughnessMaterial(name, scene) {
  46836. var _this = _super.call(this, name, scene) || this;
  46837. _this._useRoughnessFromMetallicTextureAlpha = false;
  46838. _this._useRoughnessFromMetallicTextureGreen = true;
  46839. _this._useMetallnessFromMetallicTextureBlue = true;
  46840. _this.metallic = 1.0;
  46841. _this.roughness = 1.0;
  46842. return _this;
  46843. }
  46844. /**
  46845. * Return the currrent class name of the material.
  46846. */
  46847. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46848. return "PBRMetallicRoughnessMaterial";
  46849. };
  46850. /**
  46851. * Return the active textures of the material.
  46852. */
  46853. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46854. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46855. if (this.baseTexture) {
  46856. activeTextures.push(this.baseTexture);
  46857. }
  46858. if (this.metallicRoughnessTexture) {
  46859. activeTextures.push(this.metallicRoughnessTexture);
  46860. }
  46861. return activeTextures;
  46862. };
  46863. /**
  46864. * Checks to see if a texture is used in the material.
  46865. * @param texture - Base texture to use.
  46866. * @returns - Boolean specifying if a texture is used in the material.
  46867. */
  46868. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46869. if (_super.prototype.hasTexture.call(this, texture)) {
  46870. return true;
  46871. }
  46872. if (this.baseTexture === texture) {
  46873. return true;
  46874. }
  46875. if (this.metallicRoughnessTexture === texture) {
  46876. return true;
  46877. }
  46878. return false;
  46879. };
  46880. /**
  46881. * Makes a duplicate of the current material.
  46882. * @param name - name to use for the new material.
  46883. */
  46884. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46885. var _this = this;
  46886. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46887. clone.id = name;
  46888. clone.name = name;
  46889. return clone;
  46890. };
  46891. /**
  46892. * Serialize the material to a parsable JSON object.
  46893. */
  46894. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46895. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46896. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46897. return serializationObject;
  46898. };
  46899. /**
  46900. * Parses a JSON object correponding to the serialize function.
  46901. */
  46902. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46903. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46904. };
  46905. __decorate([
  46906. BABYLON.serializeAsColor3(),
  46907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46908. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46909. __decorate([
  46910. BABYLON.serializeAsTexture(),
  46911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46912. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46913. __decorate([
  46914. BABYLON.serialize(),
  46915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46916. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46917. __decorate([
  46918. BABYLON.serialize(),
  46919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46920. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46921. __decorate([
  46922. BABYLON.serializeAsTexture(),
  46923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46924. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46925. return PBRMetallicRoughnessMaterial;
  46926. }(BABYLON.PBRBaseSimpleMaterial));
  46927. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46928. })(BABYLON || (BABYLON = {}));
  46929. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46930. var BABYLON;
  46931. (function (BABYLON) {
  46932. /**
  46933. * The PBR material of BJS following the specular glossiness convention.
  46934. *
  46935. * This fits to the PBR convention in the GLTF definition:
  46936. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46937. */
  46938. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46939. __extends(PBRSpecularGlossinessMaterial, _super);
  46940. /**
  46941. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46942. *
  46943. * @param name The material name
  46944. * @param scene The scene the material will be use in.
  46945. */
  46946. function PBRSpecularGlossinessMaterial(name, scene) {
  46947. var _this = _super.call(this, name, scene) || this;
  46948. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46949. return _this;
  46950. }
  46951. /**
  46952. * Return the currrent class name of the material.
  46953. */
  46954. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46955. return "PBRSpecularGlossinessMaterial";
  46956. };
  46957. /**
  46958. * Return the active textures of the material.
  46959. */
  46960. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46961. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46962. if (this.diffuseTexture) {
  46963. activeTextures.push(this.diffuseTexture);
  46964. }
  46965. if (this.specularGlossinessTexture) {
  46966. activeTextures.push(this.specularGlossinessTexture);
  46967. }
  46968. return activeTextures;
  46969. };
  46970. /**
  46971. * Checks to see if a texture is used in the material.
  46972. * @param texture - Base texture to use.
  46973. * @returns - Boolean specifying if a texture is used in the material.
  46974. */
  46975. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46976. if (_super.prototype.hasTexture.call(this, texture)) {
  46977. return true;
  46978. }
  46979. if (this.diffuseTexture === texture) {
  46980. return true;
  46981. }
  46982. if (this.specularGlossinessTexture === texture) {
  46983. return true;
  46984. }
  46985. return false;
  46986. };
  46987. /**
  46988. * Makes a duplicate of the current material.
  46989. * @param name - name to use for the new material.
  46990. */
  46991. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46992. var _this = this;
  46993. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46994. clone.id = name;
  46995. clone.name = name;
  46996. return clone;
  46997. };
  46998. /**
  46999. * Serialize the material to a parsable JSON object.
  47000. */
  47001. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47002. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47003. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47004. return serializationObject;
  47005. };
  47006. /**
  47007. * Parses a JSON object correponding to the serialize function.
  47008. */
  47009. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47010. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47011. };
  47012. __decorate([
  47013. BABYLON.serializeAsColor3("diffuse"),
  47014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47015. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47016. __decorate([
  47017. BABYLON.serializeAsTexture(),
  47018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47019. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47020. __decorate([
  47021. BABYLON.serializeAsColor3("specular"),
  47022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47023. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47024. __decorate([
  47025. BABYLON.serialize(),
  47026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47027. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47028. __decorate([
  47029. BABYLON.serializeAsTexture(),
  47030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47031. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47032. return PBRSpecularGlossinessMaterial;
  47033. }(BABYLON.PBRBaseSimpleMaterial));
  47034. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47035. })(BABYLON || (BABYLON = {}));
  47036. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47037. var BABYLON;
  47038. (function (BABYLON) {
  47039. BABYLON.CameraInputTypes = {};
  47040. var CameraInputsManager = /** @class */ (function () {
  47041. function CameraInputsManager(camera) {
  47042. this.attached = {};
  47043. this.camera = camera;
  47044. this.checkInputs = function () { };
  47045. }
  47046. /**
  47047. * Add an input method to a camera.
  47048. * builtin inputs example: camera.inputs.addGamepad();
  47049. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  47050. * @param input camera input method
  47051. */
  47052. CameraInputsManager.prototype.add = function (input) {
  47053. var type = input.getSimpleName();
  47054. if (this.attached[type]) {
  47055. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47056. return;
  47057. }
  47058. this.attached[type] = input;
  47059. input.camera = this.camera;
  47060. //for checkInputs, we are dynamically creating a function
  47061. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47062. if (input.checkInputs) {
  47063. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47064. }
  47065. if (this.attachedElement) {
  47066. input.attachControl(this.attachedElement);
  47067. }
  47068. };
  47069. /**
  47070. * Remove a specific input method from a camera
  47071. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47072. * @param inputToRemove camera input method
  47073. */
  47074. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47075. for (var cam in this.attached) {
  47076. var input = this.attached[cam];
  47077. if (input === inputToRemove) {
  47078. input.detachControl(this.attachedElement);
  47079. input.camera = null;
  47080. delete this.attached[cam];
  47081. this.rebuildInputCheck();
  47082. }
  47083. }
  47084. };
  47085. CameraInputsManager.prototype.removeByType = function (inputType) {
  47086. for (var cam in this.attached) {
  47087. var input = this.attached[cam];
  47088. if (input.getClassName() === inputType) {
  47089. input.detachControl(this.attachedElement);
  47090. input.camera = null;
  47091. delete this.attached[cam];
  47092. this.rebuildInputCheck();
  47093. }
  47094. }
  47095. };
  47096. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47097. var current = this.checkInputs;
  47098. return function () {
  47099. current();
  47100. fn();
  47101. };
  47102. };
  47103. CameraInputsManager.prototype.attachInput = function (input) {
  47104. if (this.attachedElement) {
  47105. input.attachControl(this.attachedElement, this.noPreventDefault);
  47106. }
  47107. };
  47108. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47109. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47110. if (this.attachedElement) {
  47111. return;
  47112. }
  47113. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47114. this.attachedElement = element;
  47115. this.noPreventDefault = noPreventDefault;
  47116. for (var cam in this.attached) {
  47117. this.attached[cam].attachControl(element, noPreventDefault);
  47118. }
  47119. };
  47120. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47121. if (disconnect === void 0) { disconnect = false; }
  47122. if (this.attachedElement !== element) {
  47123. return;
  47124. }
  47125. for (var cam in this.attached) {
  47126. this.attached[cam].detachControl(element);
  47127. if (disconnect) {
  47128. this.attached[cam].camera = null;
  47129. }
  47130. }
  47131. this.attachedElement = null;
  47132. };
  47133. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47134. this.checkInputs = function () { };
  47135. for (var cam in this.attached) {
  47136. var input = this.attached[cam];
  47137. if (input.checkInputs) {
  47138. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47139. }
  47140. }
  47141. };
  47142. /**
  47143. * Remove all attached input methods from a camera
  47144. */
  47145. CameraInputsManager.prototype.clear = function () {
  47146. if (this.attachedElement) {
  47147. this.detachElement(this.attachedElement, true);
  47148. }
  47149. this.attached = {};
  47150. this.attachedElement = null;
  47151. this.checkInputs = function () { };
  47152. };
  47153. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47154. var inputs = {};
  47155. for (var cam in this.attached) {
  47156. var input = this.attached[cam];
  47157. var res = BABYLON.SerializationHelper.Serialize(input);
  47158. inputs[input.getClassName()] = res;
  47159. }
  47160. serializedCamera.inputsmgr = inputs;
  47161. };
  47162. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47163. var parsedInputs = parsedCamera.inputsmgr;
  47164. if (parsedInputs) {
  47165. this.clear();
  47166. for (var n in parsedInputs) {
  47167. var construct = BABYLON.CameraInputTypes[n];
  47168. if (construct) {
  47169. var parsedinput = parsedInputs[n];
  47170. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47171. this.add(input);
  47172. }
  47173. }
  47174. }
  47175. else {
  47176. //2016-03-08 this part is for managing backward compatibility
  47177. for (var n in this.attached) {
  47178. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47179. if (construct) {
  47180. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47181. this.remove(this.attached[n]);
  47182. this.add(input);
  47183. }
  47184. }
  47185. }
  47186. };
  47187. return CameraInputsManager;
  47188. }());
  47189. BABYLON.CameraInputsManager = CameraInputsManager;
  47190. })(BABYLON || (BABYLON = {}));
  47191. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47192. var BABYLON;
  47193. (function (BABYLON) {
  47194. var TargetCamera = /** @class */ (function (_super) {
  47195. __extends(TargetCamera, _super);
  47196. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47197. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47198. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47199. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47200. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47201. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47202. _this.speed = 2.0;
  47203. _this.noRotationConstraint = false;
  47204. _this.lockedTarget = null;
  47205. _this._currentTarget = BABYLON.Vector3.Zero();
  47206. _this._viewMatrix = BABYLON.Matrix.Zero();
  47207. _this._camMatrix = BABYLON.Matrix.Zero();
  47208. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47209. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47210. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47211. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47212. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47213. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47214. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47215. return _this;
  47216. }
  47217. TargetCamera.prototype.getFrontPosition = function (distance) {
  47218. this.getWorldMatrix();
  47219. var direction = this.getTarget().subtract(this.position);
  47220. direction.normalize();
  47221. direction.scaleInPlace(distance);
  47222. return this.globalPosition.add(direction);
  47223. };
  47224. TargetCamera.prototype._getLockedTargetPosition = function () {
  47225. if (!this.lockedTarget) {
  47226. return null;
  47227. }
  47228. if (this.lockedTarget.absolutePosition) {
  47229. this.lockedTarget.computeWorldMatrix();
  47230. }
  47231. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47232. };
  47233. TargetCamera.prototype.storeState = function () {
  47234. this._storedPosition = this.position.clone();
  47235. this._storedRotation = this.rotation.clone();
  47236. if (this.rotationQuaternion) {
  47237. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47238. }
  47239. return _super.prototype.storeState.call(this);
  47240. };
  47241. /**
  47242. * Restored camera state. You must call storeState() first
  47243. */
  47244. TargetCamera.prototype._restoreStateValues = function () {
  47245. if (!_super.prototype._restoreStateValues.call(this)) {
  47246. return false;
  47247. }
  47248. this.position = this._storedPosition.clone();
  47249. this.rotation = this._storedRotation.clone();
  47250. if (this.rotationQuaternion) {
  47251. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47252. }
  47253. this.cameraDirection.copyFromFloats(0, 0, 0);
  47254. this.cameraRotation.copyFromFloats(0, 0);
  47255. return true;
  47256. };
  47257. // Cache
  47258. TargetCamera.prototype._initCache = function () {
  47259. _super.prototype._initCache.call(this);
  47260. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47261. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47262. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47263. };
  47264. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47265. if (!ignoreParentClass) {
  47266. _super.prototype._updateCache.call(this);
  47267. }
  47268. var lockedTargetPosition = this._getLockedTargetPosition();
  47269. if (!lockedTargetPosition) {
  47270. this._cache.lockedTarget = null;
  47271. }
  47272. else {
  47273. if (!this._cache.lockedTarget) {
  47274. this._cache.lockedTarget = lockedTargetPosition.clone();
  47275. }
  47276. else {
  47277. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47278. }
  47279. }
  47280. this._cache.rotation.copyFrom(this.rotation);
  47281. if (this.rotationQuaternion)
  47282. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47283. };
  47284. // Synchronized
  47285. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47286. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47287. return false;
  47288. }
  47289. var lockedTargetPosition = this._getLockedTargetPosition();
  47290. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47291. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47292. };
  47293. // Methods
  47294. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47295. var engine = this.getEngine();
  47296. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47297. };
  47298. // Target
  47299. TargetCamera.prototype.setTarget = function (target) {
  47300. this.upVector.normalize();
  47301. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47302. this._camMatrix.invert();
  47303. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47304. var vDir = target.subtract(this.position);
  47305. if (vDir.x >= 0.0) {
  47306. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47307. }
  47308. else {
  47309. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47310. }
  47311. this.rotation.z = 0;
  47312. if (isNaN(this.rotation.x)) {
  47313. this.rotation.x = 0;
  47314. }
  47315. if (isNaN(this.rotation.y)) {
  47316. this.rotation.y = 0;
  47317. }
  47318. if (isNaN(this.rotation.z)) {
  47319. this.rotation.z = 0;
  47320. }
  47321. if (this.rotationQuaternion) {
  47322. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47323. }
  47324. };
  47325. /**
  47326. * Return the current target position of the camera. This value is expressed in local space.
  47327. */
  47328. TargetCamera.prototype.getTarget = function () {
  47329. return this._currentTarget;
  47330. };
  47331. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47332. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47333. };
  47334. TargetCamera.prototype._updatePosition = function () {
  47335. if (this.parent) {
  47336. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47337. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47338. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47339. return;
  47340. }
  47341. this.position.addInPlace(this.cameraDirection);
  47342. };
  47343. TargetCamera.prototype._checkInputs = function () {
  47344. var needToMove = this._decideIfNeedsToMove();
  47345. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47346. // Move
  47347. if (needToMove) {
  47348. this._updatePosition();
  47349. }
  47350. // Rotate
  47351. if (needToRotate) {
  47352. this.rotation.x += this.cameraRotation.x;
  47353. this.rotation.y += this.cameraRotation.y;
  47354. //rotate, if quaternion is set and rotation was used
  47355. if (this.rotationQuaternion) {
  47356. var len = this.rotation.lengthSquared();
  47357. if (len) {
  47358. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47359. }
  47360. }
  47361. if (!this.noRotationConstraint) {
  47362. var limit = (Math.PI / 2) * 0.95;
  47363. if (this.rotation.x > limit)
  47364. this.rotation.x = limit;
  47365. if (this.rotation.x < -limit)
  47366. this.rotation.x = -limit;
  47367. }
  47368. }
  47369. // Inertia
  47370. if (needToMove) {
  47371. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47372. this.cameraDirection.x = 0;
  47373. }
  47374. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47375. this.cameraDirection.y = 0;
  47376. }
  47377. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47378. this.cameraDirection.z = 0;
  47379. }
  47380. this.cameraDirection.scaleInPlace(this.inertia);
  47381. }
  47382. if (needToRotate) {
  47383. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47384. this.cameraRotation.x = 0;
  47385. }
  47386. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47387. this.cameraRotation.y = 0;
  47388. }
  47389. this.cameraRotation.scaleInPlace(this.inertia);
  47390. }
  47391. _super.prototype._checkInputs.call(this);
  47392. };
  47393. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47394. if (this.rotationQuaternion) {
  47395. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47396. }
  47397. else {
  47398. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47399. }
  47400. //update the up vector!
  47401. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47402. };
  47403. TargetCamera.prototype._getViewMatrix = function () {
  47404. if (this.lockedTarget) {
  47405. this.setTarget(this._getLockedTargetPosition());
  47406. }
  47407. // Compute
  47408. this._updateCameraRotationMatrix();
  47409. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47410. // Computing target and final matrix
  47411. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47412. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47413. return this._viewMatrix;
  47414. };
  47415. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47416. if (this.parent) {
  47417. var parentWorldMatrix = this.parent.getWorldMatrix();
  47418. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47419. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47420. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47421. this._markSyncedWithParent();
  47422. }
  47423. else {
  47424. this._globalPosition.copyFrom(this.position);
  47425. this._globalCurrentTarget.copyFrom(target);
  47426. this._globalCurrentUpVector.copyFrom(up);
  47427. }
  47428. if (this.getScene().useRightHandedSystem) {
  47429. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47430. }
  47431. else {
  47432. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47433. }
  47434. };
  47435. /**
  47436. * @override
  47437. * Override Camera.createRigCamera
  47438. */
  47439. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47440. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47441. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47442. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47443. if (!this.rotationQuaternion) {
  47444. this.rotationQuaternion = new BABYLON.Quaternion();
  47445. }
  47446. rigCamera._cameraRigParams = {};
  47447. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47448. }
  47449. return rigCamera;
  47450. }
  47451. return null;
  47452. };
  47453. /**
  47454. * @override
  47455. * Override Camera._updateRigCameras
  47456. */
  47457. TargetCamera.prototype._updateRigCameras = function () {
  47458. var camLeft = this._rigCameras[0];
  47459. var camRight = this._rigCameras[1];
  47460. switch (this.cameraRigMode) {
  47461. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47462. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47463. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47464. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47465. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47466. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47467. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47468. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47469. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47470. camLeft.setTarget(this.getTarget());
  47471. camRight.setTarget(this.getTarget());
  47472. break;
  47473. case BABYLON.Camera.RIG_MODE_VR:
  47474. if (camLeft.rotationQuaternion) {
  47475. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47476. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47477. }
  47478. else {
  47479. camLeft.rotation.copyFrom(this.rotation);
  47480. camRight.rotation.copyFrom(this.rotation);
  47481. }
  47482. camLeft.position.copyFrom(this.position);
  47483. camRight.position.copyFrom(this.position);
  47484. break;
  47485. }
  47486. _super.prototype._updateRigCameras.call(this);
  47487. };
  47488. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47489. if (!this._rigCamTransformMatrix) {
  47490. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47491. }
  47492. var target = this.getTarget();
  47493. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47494. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47495. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47496. };
  47497. TargetCamera.prototype.getClassName = function () {
  47498. return "TargetCamera";
  47499. };
  47500. __decorate([
  47501. BABYLON.serializeAsVector3()
  47502. ], TargetCamera.prototype, "rotation", void 0);
  47503. __decorate([
  47504. BABYLON.serialize()
  47505. ], TargetCamera.prototype, "speed", void 0);
  47506. __decorate([
  47507. BABYLON.serializeAsMeshReference("lockedTargetId")
  47508. ], TargetCamera.prototype, "lockedTarget", void 0);
  47509. return TargetCamera;
  47510. }(BABYLON.Camera));
  47511. BABYLON.TargetCamera = TargetCamera;
  47512. })(BABYLON || (BABYLON = {}));
  47513. //# sourceMappingURL=babylon.targetCamera.js.map
  47514. var BABYLON;
  47515. (function (BABYLON) {
  47516. var FreeCameraMouseInput = /** @class */ (function () {
  47517. function FreeCameraMouseInput(touchEnabled) {
  47518. if (touchEnabled === void 0) { touchEnabled = true; }
  47519. this.touchEnabled = touchEnabled;
  47520. this.buttons = [0, 1, 2];
  47521. this.angularSensibility = 2000.0;
  47522. this.previousPosition = null;
  47523. }
  47524. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47525. var _this = this;
  47526. var engine = this.camera.getEngine();
  47527. if (!this._pointerInput) {
  47528. this._pointerInput = function (p, s) {
  47529. var evt = p.event;
  47530. if (engine.isInVRExclusivePointerMode) {
  47531. return;
  47532. }
  47533. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47534. return;
  47535. }
  47536. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47537. return;
  47538. }
  47539. var srcElement = (evt.srcElement || evt.target);
  47540. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47541. try {
  47542. srcElement.setPointerCapture(evt.pointerId);
  47543. }
  47544. catch (e) {
  47545. //Nothing to do with the error. Execution will continue.
  47546. }
  47547. _this.previousPosition = {
  47548. x: evt.clientX,
  47549. y: evt.clientY
  47550. };
  47551. if (!noPreventDefault) {
  47552. evt.preventDefault();
  47553. element.focus();
  47554. }
  47555. }
  47556. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47557. try {
  47558. srcElement.releasePointerCapture(evt.pointerId);
  47559. }
  47560. catch (e) {
  47561. //Nothing to do with the error.
  47562. }
  47563. _this.previousPosition = null;
  47564. if (!noPreventDefault) {
  47565. evt.preventDefault();
  47566. }
  47567. }
  47568. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47569. if (!_this.previousPosition || engine.isPointerLock) {
  47570. return;
  47571. }
  47572. var offsetX = evt.clientX - _this.previousPosition.x;
  47573. if (_this.camera.getScene().useRightHandedSystem)
  47574. offsetX *= -1;
  47575. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47576. offsetX *= -1;
  47577. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47578. var offsetY = evt.clientY - _this.previousPosition.y;
  47579. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47580. _this.previousPosition = {
  47581. x: evt.clientX,
  47582. y: evt.clientY
  47583. };
  47584. if (!noPreventDefault) {
  47585. evt.preventDefault();
  47586. }
  47587. }
  47588. };
  47589. }
  47590. this._onMouseMove = function (evt) {
  47591. if (!engine.isPointerLock) {
  47592. return;
  47593. }
  47594. if (engine.isInVRExclusivePointerMode) {
  47595. return;
  47596. }
  47597. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47598. if (_this.camera.getScene().useRightHandedSystem)
  47599. offsetX *= -1;
  47600. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47601. offsetX *= -1;
  47602. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47603. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47604. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47605. _this.previousPosition = null;
  47606. if (!noPreventDefault) {
  47607. evt.preventDefault();
  47608. }
  47609. };
  47610. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47611. element.addEventListener("mousemove", this._onMouseMove, false);
  47612. };
  47613. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47614. if (this._observer && element) {
  47615. this.camera.getScene().onPointerObservable.remove(this._observer);
  47616. if (this._onMouseMove) {
  47617. element.removeEventListener("mousemove", this._onMouseMove);
  47618. }
  47619. this._observer = null;
  47620. this._onMouseMove = null;
  47621. this.previousPosition = null;
  47622. }
  47623. };
  47624. FreeCameraMouseInput.prototype.getClassName = function () {
  47625. return "FreeCameraMouseInput";
  47626. };
  47627. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47628. return "mouse";
  47629. };
  47630. __decorate([
  47631. BABYLON.serialize()
  47632. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47633. __decorate([
  47634. BABYLON.serialize()
  47635. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47636. return FreeCameraMouseInput;
  47637. }());
  47638. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47639. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47640. })(BABYLON || (BABYLON = {}));
  47641. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47642. var BABYLON;
  47643. (function (BABYLON) {
  47644. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47645. function FreeCameraKeyboardMoveInput() {
  47646. this._keys = new Array();
  47647. this.keysUp = [38];
  47648. this.keysDown = [40];
  47649. this.keysLeft = [37];
  47650. this.keysRight = [39];
  47651. }
  47652. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47653. var _this = this;
  47654. if (this._onCanvasBlurObserver) {
  47655. return;
  47656. }
  47657. this._scene = this.camera.getScene();
  47658. this._engine = this._scene.getEngine();
  47659. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47660. _this._keys = [];
  47661. });
  47662. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47663. var evt = info.event;
  47664. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47665. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47666. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47667. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47668. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47669. var index = _this._keys.indexOf(evt.keyCode);
  47670. if (index === -1) {
  47671. _this._keys.push(evt.keyCode);
  47672. }
  47673. if (!noPreventDefault) {
  47674. evt.preventDefault();
  47675. }
  47676. }
  47677. }
  47678. else {
  47679. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47680. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47681. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47682. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47683. var index = _this._keys.indexOf(evt.keyCode);
  47684. if (index >= 0) {
  47685. _this._keys.splice(index, 1);
  47686. }
  47687. if (!noPreventDefault) {
  47688. evt.preventDefault();
  47689. }
  47690. }
  47691. }
  47692. });
  47693. };
  47694. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47695. if (this._scene) {
  47696. if (this._onKeyboardObserver) {
  47697. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47698. }
  47699. if (this._onCanvasBlurObserver) {
  47700. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47701. }
  47702. this._onKeyboardObserver = null;
  47703. this._onCanvasBlurObserver = null;
  47704. }
  47705. this._keys = [];
  47706. };
  47707. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47708. if (this._onKeyboardObserver) {
  47709. var camera = this.camera;
  47710. // Keyboard
  47711. for (var index = 0; index < this._keys.length; index++) {
  47712. var keyCode = this._keys[index];
  47713. var speed = camera._computeLocalCameraSpeed();
  47714. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47715. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47716. }
  47717. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47718. camera._localDirection.copyFromFloats(0, 0, speed);
  47719. }
  47720. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47721. camera._localDirection.copyFromFloats(speed, 0, 0);
  47722. }
  47723. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47724. camera._localDirection.copyFromFloats(0, 0, -speed);
  47725. }
  47726. if (camera.getScene().useRightHandedSystem) {
  47727. camera._localDirection.z *= -1;
  47728. }
  47729. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47730. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47731. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47732. }
  47733. }
  47734. };
  47735. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47736. return "FreeCameraKeyboardMoveInput";
  47737. };
  47738. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47739. this._keys = [];
  47740. };
  47741. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47742. return "keyboard";
  47743. };
  47744. __decorate([
  47745. BABYLON.serialize()
  47746. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47747. __decorate([
  47748. BABYLON.serialize()
  47749. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47750. __decorate([
  47751. BABYLON.serialize()
  47752. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47753. __decorate([
  47754. BABYLON.serialize()
  47755. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47756. return FreeCameraKeyboardMoveInput;
  47757. }());
  47758. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47759. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47760. })(BABYLON || (BABYLON = {}));
  47761. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47762. var BABYLON;
  47763. (function (BABYLON) {
  47764. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47765. __extends(FreeCameraInputsManager, _super);
  47766. function FreeCameraInputsManager(camera) {
  47767. return _super.call(this, camera) || this;
  47768. }
  47769. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47770. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47771. return this;
  47772. };
  47773. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47774. if (touchEnabled === void 0) { touchEnabled = true; }
  47775. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47776. return this;
  47777. };
  47778. FreeCameraInputsManager.prototype.addGamepad = function () {
  47779. this.add(new BABYLON.FreeCameraGamepadInput());
  47780. return this;
  47781. };
  47782. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47783. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47784. return this;
  47785. };
  47786. FreeCameraInputsManager.prototype.addTouch = function () {
  47787. this.add(new BABYLON.FreeCameraTouchInput());
  47788. return this;
  47789. };
  47790. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47791. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47792. return this;
  47793. };
  47794. return FreeCameraInputsManager;
  47795. }(BABYLON.CameraInputsManager));
  47796. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47797. })(BABYLON || (BABYLON = {}));
  47798. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47799. var BABYLON;
  47800. (function (BABYLON) {
  47801. var FreeCamera = /** @class */ (function (_super) {
  47802. __extends(FreeCamera, _super);
  47803. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47804. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47805. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47806. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47807. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47808. _this.checkCollisions = false;
  47809. _this.applyGravity = false;
  47810. _this._needMoveForGravity = false;
  47811. _this._oldPosition = BABYLON.Vector3.Zero();
  47812. _this._diffPosition = BABYLON.Vector3.Zero();
  47813. _this._newPosition = BABYLON.Vector3.Zero();
  47814. // Collisions
  47815. _this._collisionMask = -1;
  47816. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47817. if (collidedMesh === void 0) { collidedMesh = null; }
  47818. //TODO move this to the collision coordinator!
  47819. if (_this.getScene().workerCollisions)
  47820. newPosition.multiplyInPlace(_this._collider._radius);
  47821. var updatePosition = function (newPos) {
  47822. _this._newPosition.copyFrom(newPos);
  47823. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47824. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47825. _this.position.addInPlace(_this._diffPosition);
  47826. if (_this.onCollide && collidedMesh) {
  47827. _this.onCollide(collidedMesh);
  47828. }
  47829. }
  47830. };
  47831. updatePosition(newPosition);
  47832. };
  47833. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47834. _this.inputs.addKeyboard().addMouse();
  47835. return _this;
  47836. }
  47837. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47838. //-- begin properties for backward compatibility for inputs
  47839. /**
  47840. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47841. * Higher values reduce sensitivity.
  47842. */
  47843. get: function () {
  47844. var mouse = this.inputs.attached["mouse"];
  47845. if (mouse)
  47846. return mouse.angularSensibility;
  47847. return 0;
  47848. },
  47849. /**
  47850. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47851. * Higher values reduce sensitivity.
  47852. */
  47853. set: function (value) {
  47854. var mouse = this.inputs.attached["mouse"];
  47855. if (mouse)
  47856. mouse.angularSensibility = value;
  47857. },
  47858. enumerable: true,
  47859. configurable: true
  47860. });
  47861. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47862. get: function () {
  47863. var keyboard = this.inputs.attached["keyboard"];
  47864. if (keyboard)
  47865. return keyboard.keysUp;
  47866. return [];
  47867. },
  47868. set: function (value) {
  47869. var keyboard = this.inputs.attached["keyboard"];
  47870. if (keyboard)
  47871. keyboard.keysUp = value;
  47872. },
  47873. enumerable: true,
  47874. configurable: true
  47875. });
  47876. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47877. get: function () {
  47878. var keyboard = this.inputs.attached["keyboard"];
  47879. if (keyboard)
  47880. return keyboard.keysDown;
  47881. return [];
  47882. },
  47883. set: function (value) {
  47884. var keyboard = this.inputs.attached["keyboard"];
  47885. if (keyboard)
  47886. keyboard.keysDown = value;
  47887. },
  47888. enumerable: true,
  47889. configurable: true
  47890. });
  47891. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47892. get: function () {
  47893. var keyboard = this.inputs.attached["keyboard"];
  47894. if (keyboard)
  47895. return keyboard.keysLeft;
  47896. return [];
  47897. },
  47898. set: function (value) {
  47899. var keyboard = this.inputs.attached["keyboard"];
  47900. if (keyboard)
  47901. keyboard.keysLeft = value;
  47902. },
  47903. enumerable: true,
  47904. configurable: true
  47905. });
  47906. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47907. get: function () {
  47908. var keyboard = this.inputs.attached["keyboard"];
  47909. if (keyboard)
  47910. return keyboard.keysRight;
  47911. return [];
  47912. },
  47913. set: function (value) {
  47914. var keyboard = this.inputs.attached["keyboard"];
  47915. if (keyboard)
  47916. keyboard.keysRight = value;
  47917. },
  47918. enumerable: true,
  47919. configurable: true
  47920. });
  47921. // Controls
  47922. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47923. this.inputs.attachElement(element, noPreventDefault);
  47924. };
  47925. FreeCamera.prototype.detachControl = function (element) {
  47926. this.inputs.detachElement(element);
  47927. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47928. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47929. };
  47930. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47931. get: function () {
  47932. return this._collisionMask;
  47933. },
  47934. set: function (mask) {
  47935. this._collisionMask = !isNaN(mask) ? mask : -1;
  47936. },
  47937. enumerable: true,
  47938. configurable: true
  47939. });
  47940. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47941. var globalPosition;
  47942. if (this.parent) {
  47943. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47944. }
  47945. else {
  47946. globalPosition = this.position;
  47947. }
  47948. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47949. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47950. if (!this._collider) {
  47951. this._collider = new BABYLON.Collider();
  47952. }
  47953. this._collider._radius = this.ellipsoid;
  47954. this._collider.collisionMask = this._collisionMask;
  47955. //no need for clone, as long as gravity is not on.
  47956. var actualDisplacement = displacement;
  47957. //add gravity to the direction to prevent the dual-collision checking
  47958. if (this.applyGravity) {
  47959. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47960. actualDisplacement = displacement.add(this.getScene().gravity);
  47961. }
  47962. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47963. };
  47964. FreeCamera.prototype._checkInputs = function () {
  47965. if (!this._localDirection) {
  47966. this._localDirection = BABYLON.Vector3.Zero();
  47967. this._transformedDirection = BABYLON.Vector3.Zero();
  47968. }
  47969. this.inputs.checkInputs();
  47970. _super.prototype._checkInputs.call(this);
  47971. };
  47972. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47973. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47974. };
  47975. FreeCamera.prototype._updatePosition = function () {
  47976. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47977. this._collideWithWorld(this.cameraDirection);
  47978. }
  47979. else {
  47980. _super.prototype._updatePosition.call(this);
  47981. }
  47982. };
  47983. FreeCamera.prototype.dispose = function () {
  47984. this.inputs.clear();
  47985. _super.prototype.dispose.call(this);
  47986. };
  47987. FreeCamera.prototype.getClassName = function () {
  47988. return "FreeCamera";
  47989. };
  47990. __decorate([
  47991. BABYLON.serializeAsVector3()
  47992. ], FreeCamera.prototype, "ellipsoid", void 0);
  47993. __decorate([
  47994. BABYLON.serializeAsVector3()
  47995. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47996. __decorate([
  47997. BABYLON.serialize()
  47998. ], FreeCamera.prototype, "checkCollisions", void 0);
  47999. __decorate([
  48000. BABYLON.serialize()
  48001. ], FreeCamera.prototype, "applyGravity", void 0);
  48002. return FreeCamera;
  48003. }(BABYLON.TargetCamera));
  48004. BABYLON.FreeCamera = FreeCamera;
  48005. })(BABYLON || (BABYLON = {}));
  48006. //# sourceMappingURL=babylon.freeCamera.js.map
  48007. var BABYLON;
  48008. (function (BABYLON) {
  48009. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48010. function ArcRotateCameraKeyboardMoveInput() {
  48011. this._keys = new Array();
  48012. this.keysUp = [38];
  48013. this.keysDown = [40];
  48014. this.keysLeft = [37];
  48015. this.keysRight = [39];
  48016. this.keysReset = [220];
  48017. this.panningSensibility = 50.0;
  48018. this.zoomingSensibility = 25.0;
  48019. this.useAltToZoom = true;
  48020. }
  48021. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48022. var _this = this;
  48023. if (this._onCanvasBlurObserver) {
  48024. return;
  48025. }
  48026. this._scene = this.camera.getScene();
  48027. this._engine = this._scene.getEngine();
  48028. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48029. _this._keys = [];
  48030. });
  48031. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48032. var evt = info.event;
  48033. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48034. _this._ctrlPressed = evt.ctrlKey;
  48035. _this._altPressed = evt.altKey;
  48036. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48037. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48038. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48039. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48040. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48041. var index = _this._keys.indexOf(evt.keyCode);
  48042. if (index === -1) {
  48043. _this._keys.push(evt.keyCode);
  48044. }
  48045. if (evt.preventDefault) {
  48046. if (!noPreventDefault) {
  48047. evt.preventDefault();
  48048. }
  48049. }
  48050. }
  48051. }
  48052. else {
  48053. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48054. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48055. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48056. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48057. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48058. var index = _this._keys.indexOf(evt.keyCode);
  48059. if (index >= 0) {
  48060. _this._keys.splice(index, 1);
  48061. }
  48062. if (evt.preventDefault) {
  48063. if (!noPreventDefault) {
  48064. evt.preventDefault();
  48065. }
  48066. }
  48067. }
  48068. }
  48069. });
  48070. };
  48071. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48072. if (this._scene) {
  48073. if (this._onKeyboardObserver) {
  48074. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48075. }
  48076. if (this._onCanvasBlurObserver) {
  48077. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48078. }
  48079. this._onKeyboardObserver = null;
  48080. this._onCanvasBlurObserver = null;
  48081. }
  48082. this._keys = [];
  48083. };
  48084. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48085. if (this._onKeyboardObserver) {
  48086. var camera = this.camera;
  48087. for (var index = 0; index < this._keys.length; index++) {
  48088. var keyCode = this._keys[index];
  48089. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48090. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48091. camera.inertialPanningX -= 1 / this.panningSensibility;
  48092. }
  48093. else {
  48094. camera.inertialAlphaOffset -= 0.01;
  48095. }
  48096. }
  48097. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48098. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48099. camera.inertialPanningY += 1 / this.panningSensibility;
  48100. }
  48101. else if (this._altPressed && this.useAltToZoom) {
  48102. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48103. }
  48104. else {
  48105. camera.inertialBetaOffset -= 0.01;
  48106. }
  48107. }
  48108. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48109. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48110. camera.inertialPanningX += 1 / this.panningSensibility;
  48111. }
  48112. else {
  48113. camera.inertialAlphaOffset += 0.01;
  48114. }
  48115. }
  48116. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48117. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48118. camera.inertialPanningY -= 1 / this.panningSensibility;
  48119. }
  48120. else if (this._altPressed && this.useAltToZoom) {
  48121. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48122. }
  48123. else {
  48124. camera.inertialBetaOffset += 0.01;
  48125. }
  48126. }
  48127. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48128. camera.restoreState();
  48129. }
  48130. }
  48131. }
  48132. };
  48133. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48134. return "ArcRotateCameraKeyboardMoveInput";
  48135. };
  48136. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48137. return "keyboard";
  48138. };
  48139. __decorate([
  48140. BABYLON.serialize()
  48141. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48142. __decorate([
  48143. BABYLON.serialize()
  48144. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48145. __decorate([
  48146. BABYLON.serialize()
  48147. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48148. __decorate([
  48149. BABYLON.serialize()
  48150. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48151. __decorate([
  48152. BABYLON.serialize()
  48153. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48154. __decorate([
  48155. BABYLON.serialize()
  48156. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48157. __decorate([
  48158. BABYLON.serialize()
  48159. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48160. __decorate([
  48161. BABYLON.serialize()
  48162. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48163. return ArcRotateCameraKeyboardMoveInput;
  48164. }());
  48165. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48166. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48167. })(BABYLON || (BABYLON = {}));
  48168. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48169. var BABYLON;
  48170. (function (BABYLON) {
  48171. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48172. function ArcRotateCameraMouseWheelInput() {
  48173. this.wheelPrecision = 3.0;
  48174. /**
  48175. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48176. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48177. */
  48178. this.wheelDeltaPercentage = 0;
  48179. }
  48180. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48181. var _this = this;
  48182. this._wheel = function (p, s) {
  48183. //sanity check - this should be a PointerWheel event.
  48184. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48185. return;
  48186. var event = p.event;
  48187. var delta = 0;
  48188. if (event.wheelDelta) {
  48189. if (_this.wheelDeltaPercentage) {
  48190. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48191. if (event.wheelDelta > 0) {
  48192. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48193. }
  48194. else {
  48195. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48196. }
  48197. }
  48198. else {
  48199. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48200. }
  48201. }
  48202. else if (event.detail) {
  48203. delta = -event.detail / _this.wheelPrecision;
  48204. }
  48205. if (delta)
  48206. _this.camera.inertialRadiusOffset += delta;
  48207. if (event.preventDefault) {
  48208. if (!noPreventDefault) {
  48209. event.preventDefault();
  48210. }
  48211. }
  48212. };
  48213. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48214. };
  48215. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48216. if (this._observer && element) {
  48217. this.camera.getScene().onPointerObservable.remove(this._observer);
  48218. this._observer = null;
  48219. this._wheel = null;
  48220. }
  48221. };
  48222. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48223. return "ArcRotateCameraMouseWheelInput";
  48224. };
  48225. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48226. return "mousewheel";
  48227. };
  48228. __decorate([
  48229. BABYLON.serialize()
  48230. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48231. __decorate([
  48232. BABYLON.serialize()
  48233. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48234. return ArcRotateCameraMouseWheelInput;
  48235. }());
  48236. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48237. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48238. })(BABYLON || (BABYLON = {}));
  48239. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48240. var BABYLON;
  48241. (function (BABYLON) {
  48242. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48243. function ArcRotateCameraPointersInput() {
  48244. this.buttons = [0, 1, 2];
  48245. this.angularSensibilityX = 1000.0;
  48246. this.angularSensibilityY = 1000.0;
  48247. this.pinchPrecision = 12.0;
  48248. /**
  48249. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48250. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48251. */
  48252. this.pinchDeltaPercentage = 0;
  48253. this.panningSensibility = 1000.0;
  48254. this.multiTouchPanning = true;
  48255. this.multiTouchPanAndZoom = true;
  48256. this._isPanClick = false;
  48257. this.pinchInwards = true;
  48258. }
  48259. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48260. var _this = this;
  48261. var engine = this.camera.getEngine();
  48262. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48263. var pointA = null;
  48264. var pointB = null;
  48265. var previousPinchSquaredDistance = 0;
  48266. var initialDistance = 0;
  48267. var twoFingerActivityCount = 0;
  48268. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48269. this._pointerInput = function (p, s) {
  48270. var evt = p.event;
  48271. var isTouch = p.event.pointerType === "touch";
  48272. if (engine.isInVRExclusivePointerMode) {
  48273. return;
  48274. }
  48275. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48276. return;
  48277. }
  48278. var srcElement = (evt.srcElement || evt.target);
  48279. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48280. try {
  48281. srcElement.setPointerCapture(evt.pointerId);
  48282. }
  48283. catch (e) {
  48284. //Nothing to do with the error. Execution will continue.
  48285. }
  48286. // Manage panning with pan button click
  48287. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48288. // manage pointers
  48289. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48290. if (pointA === null) {
  48291. pointA = cacheSoloPointer;
  48292. }
  48293. else if (pointB === null) {
  48294. pointB = cacheSoloPointer;
  48295. }
  48296. if (!noPreventDefault) {
  48297. evt.preventDefault();
  48298. element.focus();
  48299. }
  48300. }
  48301. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48302. _this.camera.restoreState();
  48303. }
  48304. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48305. try {
  48306. srcElement.releasePointerCapture(evt.pointerId);
  48307. }
  48308. catch (e) {
  48309. //Nothing to do with the error.
  48310. }
  48311. cacheSoloPointer = null;
  48312. previousPinchSquaredDistance = 0;
  48313. previousMultiTouchPanPosition.isPaning = false;
  48314. previousMultiTouchPanPosition.isPinching = false;
  48315. twoFingerActivityCount = 0;
  48316. initialDistance = 0;
  48317. if (!isTouch) {
  48318. pointB = null; // Mouse and pen are mono pointer
  48319. }
  48320. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48321. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48322. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48323. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48324. if (engine._badOS) {
  48325. pointA = pointB = null;
  48326. }
  48327. else {
  48328. //only remove the impacted pointer in case of multitouch allowing on most
  48329. //platforms switching from rotate to zoom and pan seamlessly.
  48330. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48331. pointA = pointB;
  48332. pointB = null;
  48333. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48334. }
  48335. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48336. pointB = null;
  48337. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48338. }
  48339. else {
  48340. pointA = pointB = null;
  48341. }
  48342. }
  48343. if (!noPreventDefault) {
  48344. evt.preventDefault();
  48345. }
  48346. }
  48347. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48348. if (!noPreventDefault) {
  48349. evt.preventDefault();
  48350. }
  48351. // One button down
  48352. if (pointA && pointB === null && cacheSoloPointer) {
  48353. if (_this.panningSensibility !== 0 &&
  48354. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48355. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48356. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48357. }
  48358. else {
  48359. var offsetX = evt.clientX - cacheSoloPointer.x;
  48360. var offsetY = evt.clientY - cacheSoloPointer.y;
  48361. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48362. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48363. }
  48364. cacheSoloPointer.x = evt.clientX;
  48365. cacheSoloPointer.y = evt.clientY;
  48366. }
  48367. // Two buttons down: pinch/pan
  48368. else if (pointA && pointB) {
  48369. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48370. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48371. ed.x = evt.clientX;
  48372. ed.y = evt.clientY;
  48373. var direction = _this.pinchInwards ? 1 : -1;
  48374. var distX = pointA.x - pointB.x;
  48375. var distY = pointA.y - pointB.y;
  48376. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48377. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48378. if (previousPinchSquaredDistance === 0) {
  48379. initialDistance = pinchDistance;
  48380. previousPinchSquaredDistance = pinchSquaredDistance;
  48381. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48382. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48383. return;
  48384. }
  48385. if (_this.multiTouchPanAndZoom) {
  48386. if (_this.pinchDeltaPercentage) {
  48387. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48388. }
  48389. else {
  48390. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48391. (_this.pinchPrecision *
  48392. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48393. direction);
  48394. }
  48395. if (_this.panningSensibility !== 0) {
  48396. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48397. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48398. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48399. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48400. previousMultiTouchPanPosition.x = pointersCenterX;
  48401. previousMultiTouchPanPosition.y = pointersCenterY;
  48402. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48403. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48404. }
  48405. }
  48406. else {
  48407. twoFingerActivityCount++;
  48408. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48409. if (_this.pinchDeltaPercentage) {
  48410. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48411. }
  48412. else {
  48413. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48414. (_this.pinchPrecision *
  48415. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48416. direction);
  48417. }
  48418. previousMultiTouchPanPosition.isPaning = false;
  48419. previousMultiTouchPanPosition.isPinching = true;
  48420. }
  48421. else {
  48422. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48423. if (!previousMultiTouchPanPosition.isPaning) {
  48424. previousMultiTouchPanPosition.isPaning = true;
  48425. previousMultiTouchPanPosition.isPinching = false;
  48426. previousMultiTouchPanPosition.x = ed.x;
  48427. previousMultiTouchPanPosition.y = ed.y;
  48428. return;
  48429. }
  48430. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48431. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48432. }
  48433. }
  48434. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48435. previousMultiTouchPanPosition.x = ed.x;
  48436. previousMultiTouchPanPosition.y = ed.y;
  48437. }
  48438. }
  48439. previousPinchSquaredDistance = pinchSquaredDistance;
  48440. }
  48441. }
  48442. };
  48443. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48444. this._onContextMenu = function (evt) {
  48445. evt.preventDefault();
  48446. };
  48447. if (!this.camera._useCtrlForPanning) {
  48448. element.addEventListener("contextmenu", this._onContextMenu, false);
  48449. }
  48450. this._onLostFocus = function () {
  48451. //this._keys = [];
  48452. pointA = pointB = null;
  48453. previousPinchSquaredDistance = 0;
  48454. previousMultiTouchPanPosition.isPaning = false;
  48455. previousMultiTouchPanPosition.isPinching = false;
  48456. twoFingerActivityCount = 0;
  48457. cacheSoloPointer = null;
  48458. initialDistance = 0;
  48459. };
  48460. this._onMouseMove = function (evt) {
  48461. if (!engine.isPointerLock) {
  48462. return;
  48463. }
  48464. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48465. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48466. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48467. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48468. if (!noPreventDefault) {
  48469. evt.preventDefault();
  48470. }
  48471. };
  48472. this._onGestureStart = function (e) {
  48473. if (window.MSGesture === undefined) {
  48474. return;
  48475. }
  48476. if (!_this._MSGestureHandler) {
  48477. _this._MSGestureHandler = new MSGesture();
  48478. _this._MSGestureHandler.target = element;
  48479. }
  48480. _this._MSGestureHandler.addPointer(e.pointerId);
  48481. };
  48482. this._onGesture = function (e) {
  48483. _this.camera.radius *= e.scale;
  48484. if (e.preventDefault) {
  48485. if (!noPreventDefault) {
  48486. e.stopPropagation();
  48487. e.preventDefault();
  48488. }
  48489. }
  48490. };
  48491. element.addEventListener("mousemove", this._onMouseMove, false);
  48492. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48493. element.addEventListener("MSGestureChange", this._onGesture, false);
  48494. BABYLON.Tools.RegisterTopRootEvents([
  48495. { name: "blur", handler: this._onLostFocus }
  48496. ]);
  48497. };
  48498. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48499. if (this._onLostFocus) {
  48500. BABYLON.Tools.UnregisterTopRootEvents([
  48501. { name: "blur", handler: this._onLostFocus }
  48502. ]);
  48503. }
  48504. if (element && this._observer) {
  48505. this.camera.getScene().onPointerObservable.remove(this._observer);
  48506. this._observer = null;
  48507. if (this._onContextMenu) {
  48508. element.removeEventListener("contextmenu", this._onContextMenu);
  48509. }
  48510. if (this._onMouseMove) {
  48511. element.removeEventListener("mousemove", this._onMouseMove);
  48512. }
  48513. if (this._onGestureStart) {
  48514. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48515. }
  48516. if (this._onGesture) {
  48517. element.removeEventListener("MSGestureChange", this._onGesture);
  48518. }
  48519. this._isPanClick = false;
  48520. this.pinchInwards = true;
  48521. this._onMouseMove = null;
  48522. this._onGestureStart = null;
  48523. this._onGesture = null;
  48524. this._MSGestureHandler = null;
  48525. this._onLostFocus = null;
  48526. this._onContextMenu = null;
  48527. }
  48528. };
  48529. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48530. return "ArcRotateCameraPointersInput";
  48531. };
  48532. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48533. return "pointers";
  48534. };
  48535. __decorate([
  48536. BABYLON.serialize()
  48537. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48538. __decorate([
  48539. BABYLON.serialize()
  48540. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48541. __decorate([
  48542. BABYLON.serialize()
  48543. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48544. __decorate([
  48545. BABYLON.serialize()
  48546. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48547. __decorate([
  48548. BABYLON.serialize()
  48549. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48550. __decorate([
  48551. BABYLON.serialize()
  48552. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48553. __decorate([
  48554. BABYLON.serialize()
  48555. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48556. __decorate([
  48557. BABYLON.serialize()
  48558. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48559. return ArcRotateCameraPointersInput;
  48560. }());
  48561. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48562. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48563. })(BABYLON || (BABYLON = {}));
  48564. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48565. var BABYLON;
  48566. (function (BABYLON) {
  48567. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48568. __extends(ArcRotateCameraInputsManager, _super);
  48569. function ArcRotateCameraInputsManager(camera) {
  48570. return _super.call(this, camera) || this;
  48571. }
  48572. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48573. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48574. return this;
  48575. };
  48576. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48577. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48578. return this;
  48579. };
  48580. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48581. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48582. return this;
  48583. };
  48584. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48585. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48586. return this;
  48587. };
  48588. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48589. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48590. return this;
  48591. };
  48592. return ArcRotateCameraInputsManager;
  48593. }(BABYLON.CameraInputsManager));
  48594. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48595. })(BABYLON || (BABYLON = {}));
  48596. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48597. var BABYLON;
  48598. (function (BABYLON) {
  48599. var ArcRotateCamera = /** @class */ (function (_super) {
  48600. __extends(ArcRotateCamera, _super);
  48601. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48602. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48603. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48604. _this.inertialAlphaOffset = 0;
  48605. _this.inertialBetaOffset = 0;
  48606. _this.inertialRadiusOffset = 0;
  48607. _this.lowerAlphaLimit = null;
  48608. _this.upperAlphaLimit = null;
  48609. _this.lowerBetaLimit = 0.01;
  48610. _this.upperBetaLimit = Math.PI;
  48611. _this.lowerRadiusLimit = null;
  48612. _this.upperRadiusLimit = null;
  48613. _this.inertialPanningX = 0;
  48614. _this.inertialPanningY = 0;
  48615. _this.pinchToPanMaxDistance = 20;
  48616. _this.panningDistanceLimit = null;
  48617. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48618. _this.panningInertia = 0.9;
  48619. //-- end properties for backward compatibility for inputs
  48620. _this.zoomOnFactor = 1;
  48621. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48622. _this.allowUpsideDown = true;
  48623. _this._viewMatrix = new BABYLON.Matrix();
  48624. // Panning
  48625. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48626. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48627. _this.checkCollisions = false;
  48628. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48629. _this._previousPosition = BABYLON.Vector3.Zero();
  48630. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48631. _this._newPosition = BABYLON.Vector3.Zero();
  48632. _this._computationVector = BABYLON.Vector3.Zero();
  48633. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48634. if (collidedMesh === void 0) { collidedMesh = null; }
  48635. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48636. newPosition.multiplyInPlace(_this._collider._radius);
  48637. }
  48638. if (!collidedMesh) {
  48639. _this._previousPosition.copyFrom(_this.position);
  48640. }
  48641. else {
  48642. _this.setPosition(newPosition);
  48643. if (_this.onCollide) {
  48644. _this.onCollide(collidedMesh);
  48645. }
  48646. }
  48647. // Recompute because of constraints
  48648. var cosa = Math.cos(_this.alpha);
  48649. var sina = Math.sin(_this.alpha);
  48650. var cosb = Math.cos(_this.beta);
  48651. var sinb = Math.sin(_this.beta);
  48652. if (sinb === 0) {
  48653. sinb = 0.0001;
  48654. }
  48655. var target = _this._getTargetPosition();
  48656. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48657. target.addToRef(_this._computationVector, _this._newPosition);
  48658. _this.position.copyFrom(_this._newPosition);
  48659. var up = _this.upVector;
  48660. if (_this.allowUpsideDown && _this.beta < 0) {
  48661. up = up.clone();
  48662. up = up.negate();
  48663. }
  48664. _this._computeViewMatrix(_this.position, target, up);
  48665. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48666. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48667. _this._collisionTriggered = false;
  48668. };
  48669. _this._target = BABYLON.Vector3.Zero();
  48670. if (target) {
  48671. _this.setTarget(target);
  48672. }
  48673. _this.alpha = alpha;
  48674. _this.beta = beta;
  48675. _this.radius = radius;
  48676. _this.getViewMatrix();
  48677. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48678. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48679. return _this;
  48680. }
  48681. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48682. get: function () {
  48683. return this._target;
  48684. },
  48685. set: function (value) {
  48686. this.setTarget(value);
  48687. },
  48688. enumerable: true,
  48689. configurable: true
  48690. });
  48691. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48692. //-- begin properties for backward compatibility for inputs
  48693. get: function () {
  48694. var pointers = this.inputs.attached["pointers"];
  48695. if (pointers)
  48696. return pointers.angularSensibilityX;
  48697. return 0;
  48698. },
  48699. set: function (value) {
  48700. var pointers = this.inputs.attached["pointers"];
  48701. if (pointers) {
  48702. pointers.angularSensibilityX = value;
  48703. }
  48704. },
  48705. enumerable: true,
  48706. configurable: true
  48707. });
  48708. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48709. get: function () {
  48710. var pointers = this.inputs.attached["pointers"];
  48711. if (pointers)
  48712. return pointers.angularSensibilityY;
  48713. return 0;
  48714. },
  48715. set: function (value) {
  48716. var pointers = this.inputs.attached["pointers"];
  48717. if (pointers) {
  48718. pointers.angularSensibilityY = value;
  48719. }
  48720. },
  48721. enumerable: true,
  48722. configurable: true
  48723. });
  48724. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48725. get: function () {
  48726. var pointers = this.inputs.attached["pointers"];
  48727. if (pointers)
  48728. return pointers.pinchPrecision;
  48729. return 0;
  48730. },
  48731. set: function (value) {
  48732. var pointers = this.inputs.attached["pointers"];
  48733. if (pointers) {
  48734. pointers.pinchPrecision = value;
  48735. }
  48736. },
  48737. enumerable: true,
  48738. configurable: true
  48739. });
  48740. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48741. get: function () {
  48742. var pointers = this.inputs.attached["pointers"];
  48743. if (pointers)
  48744. return pointers.pinchDeltaPercentage;
  48745. return 0;
  48746. },
  48747. set: function (value) {
  48748. var pointers = this.inputs.attached["pointers"];
  48749. if (pointers) {
  48750. pointers.pinchDeltaPercentage = value;
  48751. }
  48752. },
  48753. enumerable: true,
  48754. configurable: true
  48755. });
  48756. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48757. get: function () {
  48758. var pointers = this.inputs.attached["pointers"];
  48759. if (pointers)
  48760. return pointers.panningSensibility;
  48761. return 0;
  48762. },
  48763. set: function (value) {
  48764. var pointers = this.inputs.attached["pointers"];
  48765. if (pointers) {
  48766. pointers.panningSensibility = value;
  48767. }
  48768. },
  48769. enumerable: true,
  48770. configurable: true
  48771. });
  48772. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48773. get: function () {
  48774. var keyboard = this.inputs.attached["keyboard"];
  48775. if (keyboard)
  48776. return keyboard.keysUp;
  48777. return [];
  48778. },
  48779. set: function (value) {
  48780. var keyboard = this.inputs.attached["keyboard"];
  48781. if (keyboard)
  48782. keyboard.keysUp = value;
  48783. },
  48784. enumerable: true,
  48785. configurable: true
  48786. });
  48787. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48788. get: function () {
  48789. var keyboard = this.inputs.attached["keyboard"];
  48790. if (keyboard)
  48791. return keyboard.keysDown;
  48792. return [];
  48793. },
  48794. set: function (value) {
  48795. var keyboard = this.inputs.attached["keyboard"];
  48796. if (keyboard)
  48797. keyboard.keysDown = value;
  48798. },
  48799. enumerable: true,
  48800. configurable: true
  48801. });
  48802. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48803. get: function () {
  48804. var keyboard = this.inputs.attached["keyboard"];
  48805. if (keyboard)
  48806. return keyboard.keysLeft;
  48807. return [];
  48808. },
  48809. set: function (value) {
  48810. var keyboard = this.inputs.attached["keyboard"];
  48811. if (keyboard)
  48812. keyboard.keysLeft = value;
  48813. },
  48814. enumerable: true,
  48815. configurable: true
  48816. });
  48817. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48818. get: function () {
  48819. var keyboard = this.inputs.attached["keyboard"];
  48820. if (keyboard)
  48821. return keyboard.keysRight;
  48822. return [];
  48823. },
  48824. set: function (value) {
  48825. var keyboard = this.inputs.attached["keyboard"];
  48826. if (keyboard)
  48827. keyboard.keysRight = value;
  48828. },
  48829. enumerable: true,
  48830. configurable: true
  48831. });
  48832. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48833. get: function () {
  48834. var mousewheel = this.inputs.attached["mousewheel"];
  48835. if (mousewheel)
  48836. return mousewheel.wheelPrecision;
  48837. return 0;
  48838. },
  48839. set: function (value) {
  48840. var mousewheel = this.inputs.attached["mousewheel"];
  48841. if (mousewheel)
  48842. mousewheel.wheelPrecision = value;
  48843. },
  48844. enumerable: true,
  48845. configurable: true
  48846. });
  48847. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48848. get: function () {
  48849. var mousewheel = this.inputs.attached["mousewheel"];
  48850. if (mousewheel)
  48851. return mousewheel.wheelDeltaPercentage;
  48852. return 0;
  48853. },
  48854. set: function (value) {
  48855. var mousewheel = this.inputs.attached["mousewheel"];
  48856. if (mousewheel)
  48857. mousewheel.wheelDeltaPercentage = value;
  48858. },
  48859. enumerable: true,
  48860. configurable: true
  48861. });
  48862. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48863. get: function () {
  48864. return this._bouncingBehavior;
  48865. },
  48866. enumerable: true,
  48867. configurable: true
  48868. });
  48869. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48870. get: function () {
  48871. return this._bouncingBehavior != null;
  48872. },
  48873. set: function (value) {
  48874. if (value === this.useBouncingBehavior) {
  48875. return;
  48876. }
  48877. if (value) {
  48878. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48879. this.addBehavior(this._bouncingBehavior);
  48880. }
  48881. else if (this._bouncingBehavior) {
  48882. this.removeBehavior(this._bouncingBehavior);
  48883. this._bouncingBehavior = null;
  48884. }
  48885. },
  48886. enumerable: true,
  48887. configurable: true
  48888. });
  48889. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48890. get: function () {
  48891. return this._framingBehavior;
  48892. },
  48893. enumerable: true,
  48894. configurable: true
  48895. });
  48896. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48897. get: function () {
  48898. return this._framingBehavior != null;
  48899. },
  48900. set: function (value) {
  48901. if (value === this.useFramingBehavior) {
  48902. return;
  48903. }
  48904. if (value) {
  48905. this._framingBehavior = new BABYLON.FramingBehavior();
  48906. this.addBehavior(this._framingBehavior);
  48907. }
  48908. else if (this._framingBehavior) {
  48909. this.removeBehavior(this._framingBehavior);
  48910. this._framingBehavior = null;
  48911. }
  48912. },
  48913. enumerable: true,
  48914. configurable: true
  48915. });
  48916. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48917. get: function () {
  48918. return this._autoRotationBehavior;
  48919. },
  48920. enumerable: true,
  48921. configurable: true
  48922. });
  48923. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48924. get: function () {
  48925. return this._autoRotationBehavior != null;
  48926. },
  48927. set: function (value) {
  48928. if (value === this.useAutoRotationBehavior) {
  48929. return;
  48930. }
  48931. if (value) {
  48932. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48933. this.addBehavior(this._autoRotationBehavior);
  48934. }
  48935. else if (this._autoRotationBehavior) {
  48936. this.removeBehavior(this._autoRotationBehavior);
  48937. this._autoRotationBehavior = null;
  48938. }
  48939. },
  48940. enumerable: true,
  48941. configurable: true
  48942. });
  48943. // Cache
  48944. ArcRotateCamera.prototype._initCache = function () {
  48945. _super.prototype._initCache.call(this);
  48946. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48947. this._cache.alpha = undefined;
  48948. this._cache.beta = undefined;
  48949. this._cache.radius = undefined;
  48950. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48951. };
  48952. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48953. if (!ignoreParentClass) {
  48954. _super.prototype._updateCache.call(this);
  48955. }
  48956. this._cache._target.copyFrom(this._getTargetPosition());
  48957. this._cache.alpha = this.alpha;
  48958. this._cache.beta = this.beta;
  48959. this._cache.radius = this.radius;
  48960. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48961. };
  48962. ArcRotateCamera.prototype._getTargetPosition = function () {
  48963. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48964. var pos = this._targetHost.getAbsolutePosition();
  48965. if (this._targetBoundingCenter) {
  48966. pos.addToRef(this._targetBoundingCenter, this._target);
  48967. }
  48968. else {
  48969. this._target.copyFrom(pos);
  48970. }
  48971. }
  48972. var lockedTargetPosition = this._getLockedTargetPosition();
  48973. if (lockedTargetPosition) {
  48974. return lockedTargetPosition;
  48975. }
  48976. return this._target;
  48977. };
  48978. ArcRotateCamera.prototype.storeState = function () {
  48979. this._storedAlpha = this.alpha;
  48980. this._storedBeta = this.beta;
  48981. this._storedRadius = this.radius;
  48982. this._storedTarget = this._getTargetPosition().clone();
  48983. return _super.prototype.storeState.call(this);
  48984. };
  48985. /**
  48986. * Restored camera state. You must call storeState() first
  48987. */
  48988. ArcRotateCamera.prototype._restoreStateValues = function () {
  48989. if (!_super.prototype._restoreStateValues.call(this)) {
  48990. return false;
  48991. }
  48992. this.alpha = this._storedAlpha;
  48993. this.beta = this._storedBeta;
  48994. this.radius = this._storedRadius;
  48995. this.setTarget(this._storedTarget.clone());
  48996. this.inertialAlphaOffset = 0;
  48997. this.inertialBetaOffset = 0;
  48998. this.inertialRadiusOffset = 0;
  48999. this.inertialPanningX = 0;
  49000. this.inertialPanningY = 0;
  49001. return true;
  49002. };
  49003. // Synchronized
  49004. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49005. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49006. return false;
  49007. return this._cache._target.equals(this._getTargetPosition())
  49008. && this._cache.alpha === this.alpha
  49009. && this._cache.beta === this.beta
  49010. && this._cache.radius === this.radius
  49011. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49012. };
  49013. // Methods
  49014. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49015. var _this = this;
  49016. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49017. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49018. this._useCtrlForPanning = useCtrlForPanning;
  49019. this._panningMouseButton = panningMouseButton;
  49020. this.inputs.attachElement(element, noPreventDefault);
  49021. this._reset = function () {
  49022. _this.inertialAlphaOffset = 0;
  49023. _this.inertialBetaOffset = 0;
  49024. _this.inertialRadiusOffset = 0;
  49025. _this.inertialPanningX = 0;
  49026. _this.inertialPanningY = 0;
  49027. };
  49028. };
  49029. ArcRotateCamera.prototype.detachControl = function (element) {
  49030. this.inputs.detachElement(element);
  49031. if (this._reset) {
  49032. this._reset();
  49033. }
  49034. };
  49035. ArcRotateCamera.prototype._checkInputs = function () {
  49036. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49037. if (this._collisionTriggered) {
  49038. return;
  49039. }
  49040. this.inputs.checkInputs();
  49041. // Inertia
  49042. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49043. var inertialAlphaOffset = this.inertialAlphaOffset;
  49044. if (this.beta <= 0)
  49045. inertialAlphaOffset *= -1;
  49046. if (this.getScene().useRightHandedSystem)
  49047. inertialAlphaOffset *= -1;
  49048. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49049. inertialAlphaOffset *= -1;
  49050. this.alpha += inertialAlphaOffset;
  49051. this.beta += this.inertialBetaOffset;
  49052. this.radius -= this.inertialRadiusOffset;
  49053. this.inertialAlphaOffset *= this.inertia;
  49054. this.inertialBetaOffset *= this.inertia;
  49055. this.inertialRadiusOffset *= this.inertia;
  49056. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49057. this.inertialAlphaOffset = 0;
  49058. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49059. this.inertialBetaOffset = 0;
  49060. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49061. this.inertialRadiusOffset = 0;
  49062. }
  49063. // Panning inertia
  49064. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49065. if (!this._localDirection) {
  49066. this._localDirection = BABYLON.Vector3.Zero();
  49067. this._transformedDirection = BABYLON.Vector3.Zero();
  49068. }
  49069. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49070. this._localDirection.multiplyInPlace(this.panningAxis);
  49071. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49072. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49073. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49074. if (!this.panningAxis.y) {
  49075. this._transformedDirection.y = 0;
  49076. }
  49077. if (!this._targetHost) {
  49078. if (this.panningDistanceLimit) {
  49079. this._transformedDirection.addInPlace(this._target);
  49080. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49081. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49082. this._target.copyFrom(this._transformedDirection);
  49083. }
  49084. }
  49085. else {
  49086. this._target.addInPlace(this._transformedDirection);
  49087. }
  49088. }
  49089. this.inertialPanningX *= this.panningInertia;
  49090. this.inertialPanningY *= this.panningInertia;
  49091. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49092. this.inertialPanningX = 0;
  49093. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49094. this.inertialPanningY = 0;
  49095. }
  49096. // Limits
  49097. this._checkLimits();
  49098. _super.prototype._checkInputs.call(this);
  49099. };
  49100. ArcRotateCamera.prototype._checkLimits = function () {
  49101. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49102. if (this.allowUpsideDown && this.beta > Math.PI) {
  49103. this.beta = this.beta - (2 * Math.PI);
  49104. }
  49105. }
  49106. else {
  49107. if (this.beta < this.lowerBetaLimit) {
  49108. this.beta = this.lowerBetaLimit;
  49109. }
  49110. }
  49111. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49112. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49113. this.beta = this.beta + (2 * Math.PI);
  49114. }
  49115. }
  49116. else {
  49117. if (this.beta > this.upperBetaLimit) {
  49118. this.beta = this.upperBetaLimit;
  49119. }
  49120. }
  49121. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49122. this.alpha = this.lowerAlphaLimit;
  49123. }
  49124. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49125. this.alpha = this.upperAlphaLimit;
  49126. }
  49127. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49128. this.radius = this.lowerRadiusLimit;
  49129. }
  49130. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49131. this.radius = this.upperRadiusLimit;
  49132. }
  49133. };
  49134. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49135. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49136. this.radius = this._computationVector.length();
  49137. if (this.radius === 0) {
  49138. this.radius = 0.0001; // Just to avoid division by zero
  49139. }
  49140. // Alpha
  49141. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49142. if (this._computationVector.z < 0) {
  49143. this.alpha = 2 * Math.PI - this.alpha;
  49144. }
  49145. // Beta
  49146. this.beta = Math.acos(this._computationVector.y / this.radius);
  49147. this._checkLimits();
  49148. };
  49149. ArcRotateCamera.prototype.setPosition = function (position) {
  49150. if (this.position.equals(position)) {
  49151. return;
  49152. }
  49153. this.position.copyFrom(position);
  49154. this.rebuildAnglesAndRadius();
  49155. };
  49156. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49157. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49158. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49159. if (target.getBoundingInfo) {
  49160. if (toBoundingCenter) {
  49161. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49162. }
  49163. else {
  49164. this._targetBoundingCenter = null;
  49165. }
  49166. this._targetHost = target;
  49167. this._target = this._getTargetPosition();
  49168. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49169. }
  49170. else {
  49171. var newTarget = target;
  49172. var currentTarget = this._getTargetPosition();
  49173. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49174. return;
  49175. }
  49176. this._targetHost = null;
  49177. this._target = newTarget;
  49178. this._targetBoundingCenter = null;
  49179. this.onMeshTargetChangedObservable.notifyObservers(null);
  49180. }
  49181. this.rebuildAnglesAndRadius();
  49182. };
  49183. ArcRotateCamera.prototype._getViewMatrix = function () {
  49184. // Compute
  49185. var cosa = Math.cos(this.alpha);
  49186. var sina = Math.sin(this.alpha);
  49187. var cosb = Math.cos(this.beta);
  49188. var sinb = Math.sin(this.beta);
  49189. if (sinb === 0) {
  49190. sinb = 0.0001;
  49191. }
  49192. var target = this._getTargetPosition();
  49193. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49194. target.addToRef(this._computationVector, this._newPosition);
  49195. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49196. if (!this._collider) {
  49197. this._collider = new BABYLON.Collider();
  49198. }
  49199. this._collider._radius = this.collisionRadius;
  49200. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49201. this._collisionTriggered = true;
  49202. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49203. }
  49204. else {
  49205. this.position.copyFrom(this._newPosition);
  49206. var up = this.upVector;
  49207. if (this.allowUpsideDown && sinb < 0) {
  49208. up = up.clone();
  49209. up = up.negate();
  49210. }
  49211. this._computeViewMatrix(this.position, target, up);
  49212. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49213. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49214. }
  49215. this._currentTarget = target;
  49216. return this._viewMatrix;
  49217. };
  49218. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49219. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49220. meshes = meshes || this.getScene().meshes;
  49221. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49222. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49223. this.radius = distance * this.zoomOnFactor;
  49224. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49225. };
  49226. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49227. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49228. var meshesOrMinMaxVector;
  49229. var distance;
  49230. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49231. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49232. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49233. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49234. }
  49235. else { //minMaxVector and distance
  49236. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49237. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49238. distance = minMaxVectorAndDistance.distance;
  49239. }
  49240. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49241. if (!doNotUpdateMaxZ) {
  49242. this.maxZ = distance * 2;
  49243. }
  49244. };
  49245. /**
  49246. * @override
  49247. * Override Camera.createRigCamera
  49248. */
  49249. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49250. var alphaShift = 0;
  49251. switch (this.cameraRigMode) {
  49252. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49253. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49254. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49255. case BABYLON.Camera.RIG_MODE_VR:
  49256. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49257. break;
  49258. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49259. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49260. break;
  49261. }
  49262. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49263. rigCam._cameraRigParams = {};
  49264. return rigCam;
  49265. };
  49266. /**
  49267. * @override
  49268. * Override Camera._updateRigCameras
  49269. */
  49270. ArcRotateCamera.prototype._updateRigCameras = function () {
  49271. var camLeft = this._rigCameras[0];
  49272. var camRight = this._rigCameras[1];
  49273. camLeft.beta = camRight.beta = this.beta;
  49274. camLeft.radius = camRight.radius = this.radius;
  49275. switch (this.cameraRigMode) {
  49276. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49277. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49278. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49279. case BABYLON.Camera.RIG_MODE_VR:
  49280. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49281. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49282. break;
  49283. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49284. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49285. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49286. break;
  49287. }
  49288. _super.prototype._updateRigCameras.call(this);
  49289. };
  49290. ArcRotateCamera.prototype.dispose = function () {
  49291. this.inputs.clear();
  49292. _super.prototype.dispose.call(this);
  49293. };
  49294. ArcRotateCamera.prototype.getClassName = function () {
  49295. return "ArcRotateCamera";
  49296. };
  49297. __decorate([
  49298. BABYLON.serialize()
  49299. ], ArcRotateCamera.prototype, "alpha", void 0);
  49300. __decorate([
  49301. BABYLON.serialize()
  49302. ], ArcRotateCamera.prototype, "beta", void 0);
  49303. __decorate([
  49304. BABYLON.serialize()
  49305. ], ArcRotateCamera.prototype, "radius", void 0);
  49306. __decorate([
  49307. BABYLON.serializeAsVector3("target")
  49308. ], ArcRotateCamera.prototype, "_target", void 0);
  49309. __decorate([
  49310. BABYLON.serialize()
  49311. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49312. __decorate([
  49313. BABYLON.serialize()
  49314. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49315. __decorate([
  49316. BABYLON.serialize()
  49317. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49318. __decorate([
  49319. BABYLON.serialize()
  49320. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49321. __decorate([
  49322. BABYLON.serialize()
  49323. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49324. __decorate([
  49325. BABYLON.serialize()
  49326. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49327. __decorate([
  49328. BABYLON.serialize()
  49329. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49330. __decorate([
  49331. BABYLON.serialize()
  49332. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49333. __decorate([
  49334. BABYLON.serialize()
  49335. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49336. __decorate([
  49337. BABYLON.serialize()
  49338. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49339. __decorate([
  49340. BABYLON.serialize()
  49341. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49342. __decorate([
  49343. BABYLON.serialize()
  49344. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49345. __decorate([
  49346. BABYLON.serialize()
  49347. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49348. __decorate([
  49349. BABYLON.serializeAsVector3()
  49350. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49351. __decorate([
  49352. BABYLON.serialize()
  49353. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49354. __decorate([
  49355. BABYLON.serialize()
  49356. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49357. __decorate([
  49358. BABYLON.serialize()
  49359. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49360. return ArcRotateCamera;
  49361. }(BABYLON.TargetCamera));
  49362. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49363. })(BABYLON || (BABYLON = {}));
  49364. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49365. var BABYLON;
  49366. (function (BABYLON) {
  49367. /**
  49368. * The HemisphericLight simulates the ambient environment light,
  49369. * so the passed direction is the light reflection direction, not the incoming direction.
  49370. */
  49371. var HemisphericLight = /** @class */ (function (_super) {
  49372. __extends(HemisphericLight, _super);
  49373. /**
  49374. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49375. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49376. * The HemisphericLight can't cast shadows.
  49377. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49378. * @param name The friendly name of the light
  49379. * @param direction The direction of the light reflection
  49380. * @param scene The scene the light belongs to
  49381. */
  49382. function HemisphericLight(name, direction, scene) {
  49383. var _this = _super.call(this, name, scene) || this;
  49384. /**
  49385. * The groundColor is the light in the opposite direction to the one specified during creation.
  49386. * 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.
  49387. */
  49388. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49389. _this.direction = direction || BABYLON.Vector3.Up();
  49390. return _this;
  49391. }
  49392. HemisphericLight.prototype._buildUniformLayout = function () {
  49393. this._uniformBuffer.addUniform("vLightData", 4);
  49394. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49395. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49396. this._uniformBuffer.addUniform("vLightGround", 3);
  49397. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49398. this._uniformBuffer.addUniform("depthValues", 2);
  49399. this._uniformBuffer.create();
  49400. };
  49401. /**
  49402. * Returns the string "HemisphericLight".
  49403. * @return The class name
  49404. */
  49405. HemisphericLight.prototype.getClassName = function () {
  49406. return "HemisphericLight";
  49407. };
  49408. /**
  49409. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49410. * Returns the updated direction.
  49411. * @param target The target the direction should point to
  49412. * @return The computed direction
  49413. */
  49414. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49415. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49416. return this.direction;
  49417. };
  49418. /**
  49419. * Returns the shadow generator associated to the light.
  49420. * @returns Always null for hemispheric lights because it does not support shadows.
  49421. */
  49422. HemisphericLight.prototype.getShadowGenerator = function () {
  49423. return null;
  49424. };
  49425. /**
  49426. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49427. * @param effect The effect to update
  49428. * @param lightIndex The index of the light in the effect to update
  49429. * @returns The hemispheric light
  49430. */
  49431. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49432. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49433. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49434. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49435. return this;
  49436. };
  49437. /**
  49438. * @hidden internal use only.
  49439. */
  49440. HemisphericLight.prototype._getWorldMatrix = function () {
  49441. if (!this._worldMatrix) {
  49442. this._worldMatrix = BABYLON.Matrix.Identity();
  49443. }
  49444. return this._worldMatrix;
  49445. };
  49446. /**
  49447. * Returns the integer 3.
  49448. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49449. */
  49450. HemisphericLight.prototype.getTypeID = function () {
  49451. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49452. };
  49453. __decorate([
  49454. BABYLON.serializeAsColor3()
  49455. ], HemisphericLight.prototype, "groundColor", void 0);
  49456. __decorate([
  49457. BABYLON.serializeAsVector3()
  49458. ], HemisphericLight.prototype, "direction", void 0);
  49459. return HemisphericLight;
  49460. }(BABYLON.Light));
  49461. BABYLON.HemisphericLight = HemisphericLight;
  49462. })(BABYLON || (BABYLON = {}));
  49463. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49464. var BABYLON;
  49465. (function (BABYLON) {
  49466. /**
  49467. * Base implementation IShadowLight
  49468. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49469. */
  49470. var ShadowLight = /** @class */ (function (_super) {
  49471. __extends(ShadowLight, _super);
  49472. function ShadowLight() {
  49473. var _this = _super !== null && _super.apply(this, arguments) || this;
  49474. _this._needProjectionMatrixCompute = true;
  49475. return _this;
  49476. }
  49477. ShadowLight.prototype._setPosition = function (value) {
  49478. this._position = value;
  49479. };
  49480. Object.defineProperty(ShadowLight.prototype, "position", {
  49481. /**
  49482. * Sets the position the shadow will be casted from. Also use as the light position for both
  49483. * point and spot lights.
  49484. */
  49485. get: function () {
  49486. return this._position;
  49487. },
  49488. /**
  49489. * Sets the position the shadow will be casted from. Also use as the light position for both
  49490. * point and spot lights.
  49491. */
  49492. set: function (value) {
  49493. this._setPosition(value);
  49494. },
  49495. enumerable: true,
  49496. configurable: true
  49497. });
  49498. ShadowLight.prototype._setDirection = function (value) {
  49499. this._direction = value;
  49500. };
  49501. Object.defineProperty(ShadowLight.prototype, "direction", {
  49502. /**
  49503. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49504. * Also use as the light direction on spot and directional lights.
  49505. */
  49506. get: function () {
  49507. return this._direction;
  49508. },
  49509. /**
  49510. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49511. * Also use as the light direction on spot and directional lights.
  49512. */
  49513. set: function (value) {
  49514. this._setDirection(value);
  49515. },
  49516. enumerable: true,
  49517. configurable: true
  49518. });
  49519. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49520. /**
  49521. * Gets the shadow projection clipping minimum z value.
  49522. */
  49523. get: function () {
  49524. return this._shadowMinZ;
  49525. },
  49526. /**
  49527. * Sets the shadow projection clipping minimum z value.
  49528. */
  49529. set: function (value) {
  49530. this._shadowMinZ = value;
  49531. this.forceProjectionMatrixCompute();
  49532. },
  49533. enumerable: true,
  49534. configurable: true
  49535. });
  49536. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49537. /**
  49538. * Sets the shadow projection clipping maximum z value.
  49539. */
  49540. get: function () {
  49541. return this._shadowMaxZ;
  49542. },
  49543. /**
  49544. * Gets the shadow projection clipping maximum z value.
  49545. */
  49546. set: function (value) {
  49547. this._shadowMaxZ = value;
  49548. this.forceProjectionMatrixCompute();
  49549. },
  49550. enumerable: true,
  49551. configurable: true
  49552. });
  49553. /**
  49554. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49555. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49556. */
  49557. ShadowLight.prototype.computeTransformedInformation = function () {
  49558. if (this.parent && this.parent.getWorldMatrix) {
  49559. if (!this.transformedPosition) {
  49560. this.transformedPosition = BABYLON.Vector3.Zero();
  49561. }
  49562. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49563. // In case the direction is present.
  49564. if (this.direction) {
  49565. if (!this.transformedDirection) {
  49566. this.transformedDirection = BABYLON.Vector3.Zero();
  49567. }
  49568. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49569. }
  49570. return true;
  49571. }
  49572. return false;
  49573. };
  49574. /**
  49575. * Return the depth scale used for the shadow map.
  49576. * @returns the depth scale.
  49577. */
  49578. ShadowLight.prototype.getDepthScale = function () {
  49579. return 50.0;
  49580. };
  49581. /**
  49582. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49583. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49584. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49585. */
  49586. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49587. return this.transformedDirection ? this.transformedDirection : this.direction;
  49588. };
  49589. /**
  49590. * Returns the ShadowLight absolute position in the World.
  49591. * @returns the position vector in world space
  49592. */
  49593. ShadowLight.prototype.getAbsolutePosition = function () {
  49594. return this.transformedPosition ? this.transformedPosition : this.position;
  49595. };
  49596. /**
  49597. * Sets the ShadowLight direction toward the passed target.
  49598. * @param target The point tot target in local space
  49599. * @returns the updated ShadowLight direction
  49600. */
  49601. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49602. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49603. return this.direction;
  49604. };
  49605. /**
  49606. * Returns the light rotation in euler definition.
  49607. * @returns the x y z rotation in local space.
  49608. */
  49609. ShadowLight.prototype.getRotation = function () {
  49610. this.direction.normalize();
  49611. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49612. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49613. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49614. };
  49615. /**
  49616. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49617. * @returns true if a cube texture needs to be use
  49618. */
  49619. ShadowLight.prototype.needCube = function () {
  49620. return false;
  49621. };
  49622. /**
  49623. * Detects if the projection matrix requires to be recomputed this frame.
  49624. * @returns true if it requires to be recomputed otherwise, false.
  49625. */
  49626. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49627. return this._needProjectionMatrixCompute;
  49628. };
  49629. /**
  49630. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49631. */
  49632. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49633. this._needProjectionMatrixCompute = true;
  49634. };
  49635. /**
  49636. * Get the world matrix of the sahdow lights.
  49637. * @hidden Internal Use Only
  49638. */
  49639. ShadowLight.prototype._getWorldMatrix = function () {
  49640. if (!this._worldMatrix) {
  49641. this._worldMatrix = BABYLON.Matrix.Identity();
  49642. }
  49643. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49644. return this._worldMatrix;
  49645. };
  49646. /**
  49647. * Gets the minZ used for shadow according to both the scene and the light.
  49648. * @param activeCamera The camera we are returning the min for
  49649. * @returns the depth min z
  49650. */
  49651. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49652. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49653. };
  49654. /**
  49655. * Gets the maxZ used for shadow according to both the scene and the light.
  49656. * @param activeCamera The camera we are returning the max for
  49657. * @returns the depth max z
  49658. */
  49659. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49660. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49661. };
  49662. /**
  49663. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49664. * @param matrix The materix to updated with the projection information
  49665. * @param viewMatrix The transform matrix of the light
  49666. * @param renderList The list of mesh to render in the map
  49667. * @returns The current light
  49668. */
  49669. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49670. if (this.customProjectionMatrixBuilder) {
  49671. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49672. }
  49673. else {
  49674. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49675. }
  49676. return this;
  49677. };
  49678. __decorate([
  49679. BABYLON.serializeAsVector3()
  49680. ], ShadowLight.prototype, "position", null);
  49681. __decorate([
  49682. BABYLON.serializeAsVector3()
  49683. ], ShadowLight.prototype, "direction", null);
  49684. __decorate([
  49685. BABYLON.serialize()
  49686. ], ShadowLight.prototype, "shadowMinZ", null);
  49687. __decorate([
  49688. BABYLON.serialize()
  49689. ], ShadowLight.prototype, "shadowMaxZ", null);
  49690. return ShadowLight;
  49691. }(BABYLON.Light));
  49692. BABYLON.ShadowLight = ShadowLight;
  49693. })(BABYLON || (BABYLON = {}));
  49694. //# sourceMappingURL=babylon.shadowLight.js.map
  49695. var BABYLON;
  49696. (function (BABYLON) {
  49697. /**
  49698. * A point light is a light defined by an unique point in world space.
  49699. * The light is emitted in every direction from this point.
  49700. * A good example of a point light is a standard light bulb.
  49701. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49702. */
  49703. var PointLight = /** @class */ (function (_super) {
  49704. __extends(PointLight, _super);
  49705. /**
  49706. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49707. * A PointLight emits the light in every direction.
  49708. * It can cast shadows.
  49709. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49710. * ```javascript
  49711. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49712. * ```
  49713. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49714. * @param name The light friendly name
  49715. * @param position The position of the point light in the scene
  49716. * @param scene The scene the lights belongs to
  49717. */
  49718. function PointLight(name, position, scene) {
  49719. var _this = _super.call(this, name, scene) || this;
  49720. _this._shadowAngle = Math.PI / 2;
  49721. _this.position = position;
  49722. return _this;
  49723. }
  49724. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49725. /**
  49726. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49727. * This specifies what angle the shadow will use to be created.
  49728. *
  49729. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49730. */
  49731. get: function () {
  49732. return this._shadowAngle;
  49733. },
  49734. /**
  49735. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49736. * This specifies what angle the shadow will use to be created.
  49737. *
  49738. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49739. */
  49740. set: function (value) {
  49741. this._shadowAngle = value;
  49742. this.forceProjectionMatrixCompute();
  49743. },
  49744. enumerable: true,
  49745. configurable: true
  49746. });
  49747. Object.defineProperty(PointLight.prototype, "direction", {
  49748. /**
  49749. * Gets the direction if it has been set.
  49750. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49751. */
  49752. get: function () {
  49753. return this._direction;
  49754. },
  49755. /**
  49756. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49757. */
  49758. set: function (value) {
  49759. var previousNeedCube = this.needCube();
  49760. this._direction = value;
  49761. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49762. this._shadowGenerator.recreateShadowMap();
  49763. }
  49764. },
  49765. enumerable: true,
  49766. configurable: true
  49767. });
  49768. /**
  49769. * Returns the string "PointLight"
  49770. * @returns the class name
  49771. */
  49772. PointLight.prototype.getClassName = function () {
  49773. return "PointLight";
  49774. };
  49775. /**
  49776. * Returns the integer 0.
  49777. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49778. */
  49779. PointLight.prototype.getTypeID = function () {
  49780. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49781. };
  49782. /**
  49783. * Specifies wether or not the shadowmap should be a cube texture.
  49784. * @returns true if the shadowmap needs to be a cube texture.
  49785. */
  49786. PointLight.prototype.needCube = function () {
  49787. return !this.direction;
  49788. };
  49789. /**
  49790. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49791. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49792. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49793. */
  49794. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49795. if (this.direction) {
  49796. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49797. }
  49798. else {
  49799. switch (faceIndex) {
  49800. case 0:
  49801. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49802. case 1:
  49803. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49804. case 2:
  49805. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49806. case 3:
  49807. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49808. case 4:
  49809. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49810. case 5:
  49811. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49812. }
  49813. }
  49814. return BABYLON.Vector3.Zero();
  49815. };
  49816. /**
  49817. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49818. * - fov = PI / 2
  49819. * - aspect ratio : 1.0
  49820. * - z-near and far equal to the active camera minZ and maxZ.
  49821. * Returns the PointLight.
  49822. */
  49823. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49824. var activeCamera = this.getScene().activeCamera;
  49825. if (!activeCamera) {
  49826. return;
  49827. }
  49828. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49829. };
  49830. PointLight.prototype._buildUniformLayout = function () {
  49831. this._uniformBuffer.addUniform("vLightData", 4);
  49832. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49833. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49834. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49835. this._uniformBuffer.addUniform("depthValues", 2);
  49836. this._uniformBuffer.create();
  49837. };
  49838. /**
  49839. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49840. * @param effect The effect to update
  49841. * @param lightIndex The index of the light in the effect to update
  49842. * @returns The point light
  49843. */
  49844. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49845. if (this.computeTransformedInformation()) {
  49846. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49847. return this;
  49848. }
  49849. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49850. return this;
  49851. };
  49852. __decorate([
  49853. BABYLON.serialize()
  49854. ], PointLight.prototype, "shadowAngle", null);
  49855. return PointLight;
  49856. }(BABYLON.ShadowLight));
  49857. BABYLON.PointLight = PointLight;
  49858. })(BABYLON || (BABYLON = {}));
  49859. //# sourceMappingURL=babylon.pointLight.js.map
  49860. var BABYLON;
  49861. (function (BABYLON) {
  49862. /**
  49863. * A directional light is defined by a direction (what a surprise!).
  49864. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49865. * 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.
  49866. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49867. */
  49868. var DirectionalLight = /** @class */ (function (_super) {
  49869. __extends(DirectionalLight, _super);
  49870. /**
  49871. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49872. * The directional light is emitted from everywhere in the given direction.
  49873. * It can cast shawdows.
  49874. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49875. * @param name The friendly name of the light
  49876. * @param direction The direction of the light
  49877. * @param scene The scene the light belongs to
  49878. */
  49879. function DirectionalLight(name, direction, scene) {
  49880. var _this = _super.call(this, name, scene) || this;
  49881. _this._shadowFrustumSize = 0;
  49882. _this._shadowOrthoScale = 0.1;
  49883. /**
  49884. * Automatically compute the projection matrix to best fit (including all the casters)
  49885. * on each frame.
  49886. */
  49887. _this.autoUpdateExtends = true;
  49888. // Cache
  49889. _this._orthoLeft = Number.MAX_VALUE;
  49890. _this._orthoRight = Number.MIN_VALUE;
  49891. _this._orthoTop = Number.MIN_VALUE;
  49892. _this._orthoBottom = Number.MAX_VALUE;
  49893. _this.position = direction.scale(-1.0);
  49894. _this.direction = direction;
  49895. return _this;
  49896. }
  49897. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49898. /**
  49899. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49900. */
  49901. get: function () {
  49902. return this._shadowFrustumSize;
  49903. },
  49904. /**
  49905. * Specifies a fix frustum size for the shadow generation.
  49906. */
  49907. set: function (value) {
  49908. this._shadowFrustumSize = value;
  49909. this.forceProjectionMatrixCompute();
  49910. },
  49911. enumerable: true,
  49912. configurable: true
  49913. });
  49914. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49915. /**
  49916. * Gets the shadow projection scale against the optimal computed one.
  49917. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49918. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49919. */
  49920. get: function () {
  49921. return this._shadowOrthoScale;
  49922. },
  49923. /**
  49924. * Sets the shadow projection scale against the optimal computed one.
  49925. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49926. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49927. */
  49928. set: function (value) {
  49929. this._shadowOrthoScale = value;
  49930. this.forceProjectionMatrixCompute();
  49931. },
  49932. enumerable: true,
  49933. configurable: true
  49934. });
  49935. /**
  49936. * Returns the string "DirectionalLight".
  49937. * @return The class name
  49938. */
  49939. DirectionalLight.prototype.getClassName = function () {
  49940. return "DirectionalLight";
  49941. };
  49942. /**
  49943. * Returns the integer 1.
  49944. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49945. */
  49946. DirectionalLight.prototype.getTypeID = function () {
  49947. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49948. };
  49949. /**
  49950. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49951. * Returns the DirectionalLight Shadow projection matrix.
  49952. */
  49953. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49954. if (this.shadowFrustumSize > 0) {
  49955. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49956. }
  49957. else {
  49958. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49959. }
  49960. };
  49961. /**
  49962. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49963. * Returns the DirectionalLight Shadow projection matrix.
  49964. */
  49965. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49966. var activeCamera = this.getScene().activeCamera;
  49967. if (!activeCamera) {
  49968. return;
  49969. }
  49970. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49971. };
  49972. /**
  49973. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49974. * Returns the DirectionalLight Shadow projection matrix.
  49975. */
  49976. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49977. var activeCamera = this.getScene().activeCamera;
  49978. if (!activeCamera) {
  49979. return;
  49980. }
  49981. // Check extends
  49982. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49983. var tempVector3 = BABYLON.Vector3.Zero();
  49984. this._orthoLeft = Number.MAX_VALUE;
  49985. this._orthoRight = Number.MIN_VALUE;
  49986. this._orthoTop = Number.MIN_VALUE;
  49987. this._orthoBottom = Number.MAX_VALUE;
  49988. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49989. var mesh = renderList[meshIndex];
  49990. if (!mesh) {
  49991. continue;
  49992. }
  49993. var boundingInfo = mesh.getBoundingInfo();
  49994. var boundingBox = boundingInfo.boundingBox;
  49995. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49996. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49997. if (tempVector3.x < this._orthoLeft)
  49998. this._orthoLeft = tempVector3.x;
  49999. if (tempVector3.y < this._orthoBottom)
  50000. this._orthoBottom = tempVector3.y;
  50001. if (tempVector3.x > this._orthoRight)
  50002. this._orthoRight = tempVector3.x;
  50003. if (tempVector3.y > this._orthoTop)
  50004. this._orthoTop = tempVector3.y;
  50005. }
  50006. }
  50007. }
  50008. var xOffset = this._orthoRight - this._orthoLeft;
  50009. var yOffset = this._orthoTop - this._orthoBottom;
  50010. 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);
  50011. };
  50012. DirectionalLight.prototype._buildUniformLayout = function () {
  50013. this._uniformBuffer.addUniform("vLightData", 4);
  50014. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50015. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50016. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50017. this._uniformBuffer.addUniform("depthValues", 2);
  50018. this._uniformBuffer.create();
  50019. };
  50020. /**
  50021. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50022. * @param effect The effect to update
  50023. * @param lightIndex The index of the light in the effect to update
  50024. * @returns The directional light
  50025. */
  50026. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50027. if (this.computeTransformedInformation()) {
  50028. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50029. return this;
  50030. }
  50031. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50032. return this;
  50033. };
  50034. /**
  50035. * Gets the minZ used for shadow according to both the scene and the light.
  50036. *
  50037. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50038. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50039. * @param activeCamera The camera we are returning the min for
  50040. * @returns the depth min z
  50041. */
  50042. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50043. return 1;
  50044. };
  50045. /**
  50046. * Gets the maxZ used for shadow according to both the scene and the light.
  50047. *
  50048. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50049. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50050. * @param activeCamera The camera we are returning the max for
  50051. * @returns the depth max z
  50052. */
  50053. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50054. return 1;
  50055. };
  50056. __decorate([
  50057. BABYLON.serialize()
  50058. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50059. __decorate([
  50060. BABYLON.serialize()
  50061. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50062. __decorate([
  50063. BABYLON.serialize()
  50064. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50065. return DirectionalLight;
  50066. }(BABYLON.ShadowLight));
  50067. BABYLON.DirectionalLight = DirectionalLight;
  50068. })(BABYLON || (BABYLON = {}));
  50069. //# sourceMappingURL=babylon.directionalLight.js.map
  50070. var BABYLON;
  50071. (function (BABYLON) {
  50072. /**
  50073. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50074. * These values define a cone of light starting from the position, emitting toward the direction.
  50075. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50076. * and the exponent defines the speed of the decay of the light with distance (reach).
  50077. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50078. */
  50079. var SpotLight = /** @class */ (function (_super) {
  50080. __extends(SpotLight, _super);
  50081. /**
  50082. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50083. * It can cast shadows.
  50084. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50085. * @param name The light friendly name
  50086. * @param position The position of the spot light in the scene
  50087. * @param direction The direction of the light in the scene
  50088. * @param angle The cone angle of the light in Radians
  50089. * @param exponent The light decay speed with the distance from the emission spot
  50090. * @param scene The scene the lights belongs to
  50091. */
  50092. function SpotLight(name, position, direction, angle, exponent, scene) {
  50093. var _this = _super.call(this, name, scene) || this;
  50094. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50095. _this._projectionTextureLightNear = 1e-6;
  50096. _this._projectionTextureLightFar = 1000.0;
  50097. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50098. _this._projectionTextureViewLightDirty = true;
  50099. _this._projectionTextureProjectionLightDirty = true;
  50100. _this._projectionTextureDirty = true;
  50101. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50102. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50103. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50104. _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);
  50105. _this.position = position;
  50106. _this.direction = direction;
  50107. _this.angle = angle;
  50108. _this.exponent = exponent;
  50109. return _this;
  50110. }
  50111. Object.defineProperty(SpotLight.prototype, "angle", {
  50112. /**
  50113. * Gets the cone angle of the spot light in Radians.
  50114. */
  50115. get: function () {
  50116. return this._angle;
  50117. },
  50118. /**
  50119. * Sets the cone angle of the spot light in Radians.
  50120. */
  50121. set: function (value) {
  50122. this._angle = value;
  50123. this._projectionTextureProjectionLightDirty = true;
  50124. this.forceProjectionMatrixCompute();
  50125. },
  50126. enumerable: true,
  50127. configurable: true
  50128. });
  50129. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50130. /**
  50131. * Allows scaling the angle of the light for shadow generation only.
  50132. */
  50133. get: function () {
  50134. return this._shadowAngleScale;
  50135. },
  50136. /**
  50137. * Allows scaling the angle of the light for shadow generation only.
  50138. */
  50139. set: function (value) {
  50140. this._shadowAngleScale = value;
  50141. this.forceProjectionMatrixCompute();
  50142. },
  50143. enumerable: true,
  50144. configurable: true
  50145. });
  50146. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50147. /**
  50148. * Allows reading the projecton texture
  50149. */
  50150. get: function () {
  50151. return this._projectionTextureMatrix;
  50152. },
  50153. enumerable: true,
  50154. configurable: true
  50155. });
  50156. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50157. /**
  50158. * Gets the near clip of the Spotlight for texture projection.
  50159. */
  50160. get: function () {
  50161. return this._projectionTextureLightNear;
  50162. },
  50163. /**
  50164. * Sets the near clip of the Spotlight for texture projection.
  50165. */
  50166. set: function (value) {
  50167. this._projectionTextureLightNear = value;
  50168. this._projectionTextureProjectionLightDirty = true;
  50169. },
  50170. enumerable: true,
  50171. configurable: true
  50172. });
  50173. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50174. /**
  50175. * Gets the far clip of the Spotlight for texture projection.
  50176. */
  50177. get: function () {
  50178. return this._projectionTextureLightFar;
  50179. },
  50180. /**
  50181. * Sets the far clip of the Spotlight for texture projection.
  50182. */
  50183. set: function (value) {
  50184. this._projectionTextureLightFar = value;
  50185. this._projectionTextureProjectionLightDirty = true;
  50186. },
  50187. enumerable: true,
  50188. configurable: true
  50189. });
  50190. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50191. /**
  50192. * Gets the Up vector of the Spotlight for texture projection.
  50193. */
  50194. get: function () {
  50195. return this._projectionTextureUpDirection;
  50196. },
  50197. /**
  50198. * Sets the Up vector of the Spotlight for texture projection.
  50199. */
  50200. set: function (value) {
  50201. this._projectionTextureUpDirection = value;
  50202. this._projectionTextureProjectionLightDirty = true;
  50203. },
  50204. enumerable: true,
  50205. configurable: true
  50206. });
  50207. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50208. /**
  50209. * Gets the projection texture of the light.
  50210. */
  50211. get: function () {
  50212. return this._projectionTexture;
  50213. },
  50214. /**
  50215. * Sets the projection texture of the light.
  50216. */
  50217. set: function (value) {
  50218. this._projectionTexture = value;
  50219. this._projectionTextureDirty = true;
  50220. },
  50221. enumerable: true,
  50222. configurable: true
  50223. });
  50224. /**
  50225. * Returns the string "SpotLight".
  50226. * @returns the class name
  50227. */
  50228. SpotLight.prototype.getClassName = function () {
  50229. return "SpotLight";
  50230. };
  50231. /**
  50232. * Returns the integer 2.
  50233. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50234. */
  50235. SpotLight.prototype.getTypeID = function () {
  50236. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50237. };
  50238. /**
  50239. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50240. */
  50241. SpotLight.prototype._setDirection = function (value) {
  50242. _super.prototype._setDirection.call(this, value);
  50243. this._projectionTextureViewLightDirty = true;
  50244. };
  50245. /**
  50246. * Overrides the position setter to recompute the projection texture view light Matrix.
  50247. */
  50248. SpotLight.prototype._setPosition = function (value) {
  50249. _super.prototype._setPosition.call(this, value);
  50250. this._projectionTextureViewLightDirty = true;
  50251. };
  50252. /**
  50253. * 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.
  50254. * Returns the SpotLight.
  50255. */
  50256. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50257. var activeCamera = this.getScene().activeCamera;
  50258. if (!activeCamera) {
  50259. return;
  50260. }
  50261. this._shadowAngleScale = this._shadowAngleScale || 1;
  50262. var angle = this._shadowAngleScale * this._angle;
  50263. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50264. };
  50265. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50266. this._projectionTextureViewLightDirty = false;
  50267. this._projectionTextureDirty = true;
  50268. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50269. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50270. };
  50271. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50272. this._projectionTextureProjectionLightDirty = false;
  50273. this._projectionTextureDirty = true;
  50274. var light_far = this.projectionTextureLightFar;
  50275. var light_near = this.projectionTextureLightNear;
  50276. var P = light_far / (light_far - light_near);
  50277. var Q = -P * light_near;
  50278. var S = 1.0 / Math.tan(this._angle / 2.0);
  50279. var A = 1.0;
  50280. 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);
  50281. };
  50282. /**
  50283. * Main function for light texture projection matrix computing.
  50284. */
  50285. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50286. this._projectionTextureDirty = false;
  50287. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50288. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50289. };
  50290. SpotLight.prototype._buildUniformLayout = function () {
  50291. this._uniformBuffer.addUniform("vLightData", 4);
  50292. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50293. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50294. this._uniformBuffer.addUniform("vLightDirection", 3);
  50295. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50296. this._uniformBuffer.addUniform("depthValues", 2);
  50297. this._uniformBuffer.create();
  50298. };
  50299. /**
  50300. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50301. * @param effect The effect to update
  50302. * @param lightIndex The index of the light in the effect to update
  50303. * @returns The spot light
  50304. */
  50305. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50306. var normalizeDirection;
  50307. if (this.computeTransformedInformation()) {
  50308. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50309. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50310. }
  50311. else {
  50312. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50313. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50314. }
  50315. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50316. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50317. if (this._projectionTextureViewLightDirty) {
  50318. this._computeProjectionTextureViewLightMatrix();
  50319. }
  50320. if (this._projectionTextureProjectionLightDirty) {
  50321. this._computeProjectionTextureProjectionLightMatrix();
  50322. }
  50323. if (this._projectionTextureDirty) {
  50324. this._computeProjectionTextureMatrix();
  50325. }
  50326. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50327. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50328. }
  50329. return this;
  50330. };
  50331. /**
  50332. * Disposes the light and the associated resources.
  50333. */
  50334. SpotLight.prototype.dispose = function () {
  50335. _super.prototype.dispose.call(this);
  50336. if (this._projectionTexture) {
  50337. this._projectionTexture.dispose();
  50338. }
  50339. };
  50340. __decorate([
  50341. BABYLON.serialize()
  50342. ], SpotLight.prototype, "angle", null);
  50343. __decorate([
  50344. BABYLON.serialize()
  50345. ], SpotLight.prototype, "shadowAngleScale", null);
  50346. __decorate([
  50347. BABYLON.serialize()
  50348. ], SpotLight.prototype, "exponent", void 0);
  50349. __decorate([
  50350. BABYLON.serialize()
  50351. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50352. __decorate([
  50353. BABYLON.serialize()
  50354. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50355. __decorate([
  50356. BABYLON.serialize()
  50357. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50358. __decorate([
  50359. BABYLON.serializeAsTexture("projectedLightTexture")
  50360. ], SpotLight.prototype, "_projectionTexture", void 0);
  50361. return SpotLight;
  50362. }(BABYLON.ShadowLight));
  50363. BABYLON.SpotLight = SpotLight;
  50364. })(BABYLON || (BABYLON = {}));
  50365. //# sourceMappingURL=babylon.spotLight.js.map
  50366. var BABYLON;
  50367. (function (BABYLON) {
  50368. /**
  50369. * Class used to override all child animations of a given target
  50370. */
  50371. var AnimationPropertiesOverride = /** @class */ (function () {
  50372. function AnimationPropertiesOverride() {
  50373. /**
  50374. * Gets or sets a value indicating if animation blending must be used
  50375. */
  50376. this.enableBlending = false;
  50377. /**
  50378. * Gets or sets the blending speed to use when enableBlending is true
  50379. */
  50380. this.blendingSpeed = 0.01;
  50381. /**
  50382. * Gets or sets the default loop mode to use
  50383. */
  50384. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50385. }
  50386. return AnimationPropertiesOverride;
  50387. }());
  50388. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50389. })(BABYLON || (BABYLON = {}));
  50390. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50391. var BABYLON;
  50392. (function (BABYLON) {
  50393. /**
  50394. * Represents the range of an animation
  50395. */
  50396. var AnimationRange = /** @class */ (function () {
  50397. /**
  50398. * Initializes the range of an animation
  50399. * @param name The name of the animation range
  50400. * @param from The starting frame of the animation
  50401. * @param to The ending frame of the animation
  50402. */
  50403. function AnimationRange(
  50404. /**The name of the animation range**/
  50405. name,
  50406. /**The starting frame of the animation */
  50407. from,
  50408. /**The ending frame of the animation*/
  50409. to) {
  50410. this.name = name;
  50411. this.from = from;
  50412. this.to = to;
  50413. }
  50414. /**
  50415. * Makes a copy of the animation range
  50416. * @returns A copy of the animation range
  50417. */
  50418. AnimationRange.prototype.clone = function () {
  50419. return new AnimationRange(this.name, this.from, this.to);
  50420. };
  50421. return AnimationRange;
  50422. }());
  50423. BABYLON.AnimationRange = AnimationRange;
  50424. /**
  50425. * Composed of a frame, and an action function
  50426. */
  50427. var AnimationEvent = /** @class */ (function () {
  50428. /**
  50429. * Initializes the animation event
  50430. * @param frame The frame for which the event is triggered
  50431. * @param action The event to perform when triggered
  50432. * @param onlyOnce Specifies if the event should be triggered only once
  50433. */
  50434. function AnimationEvent(
  50435. /** The frame for which the event is triggered **/
  50436. frame,
  50437. /** The event to perform when triggered **/
  50438. action,
  50439. /** Specifies if the event should be triggered only once**/
  50440. onlyOnce) {
  50441. this.frame = frame;
  50442. this.action = action;
  50443. this.onlyOnce = onlyOnce;
  50444. /**
  50445. * Specifies if the animation event is done
  50446. */
  50447. this.isDone = false;
  50448. }
  50449. /** @hidden */
  50450. AnimationEvent.prototype._clone = function () {
  50451. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50452. };
  50453. return AnimationEvent;
  50454. }());
  50455. BABYLON.AnimationEvent = AnimationEvent;
  50456. /**
  50457. * A cursor which tracks a point on a path
  50458. */
  50459. var PathCursor = /** @class */ (function () {
  50460. /**
  50461. * Initializes the path cursor
  50462. * @param path The path to track
  50463. */
  50464. function PathCursor(path) {
  50465. this.path = path;
  50466. /**
  50467. * Stores path cursor callbacks for when an onchange event is triggered
  50468. */
  50469. this._onchange = new Array();
  50470. /**
  50471. * The value of the path cursor
  50472. */
  50473. this.value = 0;
  50474. /**
  50475. * The animation array of the path cursor
  50476. */
  50477. this.animations = new Array();
  50478. }
  50479. /**
  50480. * Gets the cursor point on the path
  50481. * @returns A point on the path cursor at the cursor location
  50482. */
  50483. PathCursor.prototype.getPoint = function () {
  50484. var point = this.path.getPointAtLengthPosition(this.value);
  50485. return new BABYLON.Vector3(point.x, 0, point.y);
  50486. };
  50487. /**
  50488. * Moves the cursor ahead by the step amount
  50489. * @param step The amount to move the cursor forward
  50490. * @returns This path cursor
  50491. */
  50492. PathCursor.prototype.moveAhead = function (step) {
  50493. if (step === void 0) { step = 0.002; }
  50494. this.move(step);
  50495. return this;
  50496. };
  50497. /**
  50498. * Moves the cursor behind by the step amount
  50499. * @param step The amount to move the cursor back
  50500. * @returns This path cursor
  50501. */
  50502. PathCursor.prototype.moveBack = function (step) {
  50503. if (step === void 0) { step = 0.002; }
  50504. this.move(-step);
  50505. return this;
  50506. };
  50507. /**
  50508. * Moves the cursor by the step amount
  50509. * If the step amount is greater than one, an exception is thrown
  50510. * @param step The amount to move the cursor
  50511. * @returns This path cursor
  50512. */
  50513. PathCursor.prototype.move = function (step) {
  50514. if (Math.abs(step) > 1) {
  50515. throw "step size should be less than 1.";
  50516. }
  50517. this.value += step;
  50518. this.ensureLimits();
  50519. this.raiseOnChange();
  50520. return this;
  50521. };
  50522. /**
  50523. * Ensures that the value is limited between zero and one
  50524. * @returns This path cursor
  50525. */
  50526. PathCursor.prototype.ensureLimits = function () {
  50527. while (this.value > 1) {
  50528. this.value -= 1;
  50529. }
  50530. while (this.value < 0) {
  50531. this.value += 1;
  50532. }
  50533. return this;
  50534. };
  50535. /**
  50536. * Runs onchange callbacks on change (used by the animation engine)
  50537. * @returns This path cursor
  50538. */
  50539. PathCursor.prototype.raiseOnChange = function () {
  50540. var _this = this;
  50541. this._onchange.forEach(function (f) { return f(_this); });
  50542. return this;
  50543. };
  50544. /**
  50545. * Executes a function on change
  50546. * @param f A path cursor onchange callback
  50547. * @returns This path cursor
  50548. */
  50549. PathCursor.prototype.onchange = function (f) {
  50550. this._onchange.push(f);
  50551. return this;
  50552. };
  50553. return PathCursor;
  50554. }());
  50555. BABYLON.PathCursor = PathCursor;
  50556. /**
  50557. * Enum for the animation key frame interpolation type
  50558. */
  50559. var AnimationKeyInterpolation;
  50560. (function (AnimationKeyInterpolation) {
  50561. /**
  50562. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50563. */
  50564. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50565. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50566. /**
  50567. * Class used to store any kind of animation
  50568. */
  50569. var Animation = /** @class */ (function () {
  50570. /**
  50571. * Initializes the animation
  50572. * @param name Name of the animation
  50573. * @param targetProperty Property to animate
  50574. * @param framePerSecond The frames per second of the animation
  50575. * @param dataType The data type of the animation
  50576. * @param loopMode The loop mode of the animation
  50577. * @param enableBlendings Specifies if blending should be enabled
  50578. */
  50579. function Animation(
  50580. /**Name of the animation */
  50581. name,
  50582. /**Property to animate */
  50583. targetProperty,
  50584. /**The frames per second of the animation */
  50585. framePerSecond,
  50586. /**The data type of the animation */
  50587. dataType,
  50588. /**The loop mode of the animation */
  50589. loopMode,
  50590. /**Specifies if blending should be enabled */
  50591. enableBlending) {
  50592. this.name = name;
  50593. this.targetProperty = targetProperty;
  50594. this.framePerSecond = framePerSecond;
  50595. this.dataType = dataType;
  50596. this.loopMode = loopMode;
  50597. this.enableBlending = enableBlending;
  50598. /**
  50599. * @hidden Internal use only
  50600. */
  50601. this._runtimeAnimations = new Array();
  50602. /**
  50603. * The set of event that will be linked to this animation
  50604. */
  50605. this._events = new Array();
  50606. /**
  50607. * Stores the blending speed of the animation
  50608. */
  50609. this.blendingSpeed = 0.01;
  50610. /**
  50611. * Stores the animation ranges for the animation
  50612. */
  50613. this._ranges = {};
  50614. this.targetPropertyPath = targetProperty.split(".");
  50615. this.dataType = dataType;
  50616. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50617. }
  50618. /**
  50619. * @hidden Internal use
  50620. */
  50621. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50622. var dataType = undefined;
  50623. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50624. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50625. }
  50626. else if (from instanceof BABYLON.Quaternion) {
  50627. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50628. }
  50629. else if (from instanceof BABYLON.Vector3) {
  50630. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50631. }
  50632. else if (from instanceof BABYLON.Vector2) {
  50633. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50634. }
  50635. else if (from instanceof BABYLON.Color3) {
  50636. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50637. }
  50638. else if (from instanceof BABYLON.Size) {
  50639. dataType = Animation.ANIMATIONTYPE_SIZE;
  50640. }
  50641. if (dataType == undefined) {
  50642. return null;
  50643. }
  50644. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50645. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50646. animation.setKeys(keys);
  50647. if (easingFunction !== undefined) {
  50648. animation.setEasingFunction(easingFunction);
  50649. }
  50650. return animation;
  50651. };
  50652. /**
  50653. * Sets up an animation
  50654. * @param property The property to animate
  50655. * @param animationType The animation type to apply
  50656. * @param framePerSecond The frames per second of the animation
  50657. * @param easingFunction The easing function used in the animation
  50658. * @returns The created animation
  50659. */
  50660. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50661. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50662. animation.setEasingFunction(easingFunction);
  50663. return animation;
  50664. };
  50665. /**
  50666. * Create and start an animation on a node
  50667. * @param name defines the name of the global animation that will be run on all nodes
  50668. * @param node defines the root node where the animation will take place
  50669. * @param targetProperty defines property to animate
  50670. * @param framePerSecond defines the number of frame per second yo use
  50671. * @param totalFrame defines the number of frames in total
  50672. * @param from defines the initial value
  50673. * @param to defines the final value
  50674. * @param loopMode defines which loop mode you want to use (off by default)
  50675. * @param easingFunction defines the easing function to use (linear by default)
  50676. * @param onAnimationEnd defines the callback to call when animation end
  50677. * @returns the animatable created for this animation
  50678. */
  50679. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50680. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50681. if (!animation) {
  50682. return null;
  50683. }
  50684. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50685. };
  50686. /**
  50687. * Create and start an animation on a node and its descendants
  50688. * @param name defines the name of the global animation that will be run on all nodes
  50689. * @param node defines the root node where the animation will take place
  50690. * @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
  50691. * @param targetProperty defines property to animate
  50692. * @param framePerSecond defines the number of frame per second to use
  50693. * @param totalFrame defines the number of frames in total
  50694. * @param from defines the initial value
  50695. * @param to defines the final value
  50696. * @param loopMode defines which loop mode you want to use (off by default)
  50697. * @param easingFunction defines the easing function to use (linear by default)
  50698. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50699. * @returns the list of animatables created for all nodes
  50700. * @example https://www.babylonjs-playground.com/#MH0VLI
  50701. */
  50702. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50703. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50704. if (!animation) {
  50705. return null;
  50706. }
  50707. var scene = node.getScene();
  50708. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50709. };
  50710. /**
  50711. * Creates a new animation, merges it with the existing animations and starts it
  50712. * @param name Name of the animation
  50713. * @param node Node which contains the scene that begins the animations
  50714. * @param targetProperty Specifies which property to animate
  50715. * @param framePerSecond The frames per second of the animation
  50716. * @param totalFrame The total number of frames
  50717. * @param from The frame at the beginning of the animation
  50718. * @param to The frame at the end of the animation
  50719. * @param loopMode Specifies the loop mode of the animation
  50720. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50721. * @param onAnimationEnd Callback to run once the animation is complete
  50722. * @returns Nullable animation
  50723. */
  50724. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50725. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50726. if (!animation) {
  50727. return null;
  50728. }
  50729. node.animations.push(animation);
  50730. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50731. };
  50732. /**
  50733. * Transition property of an host to the target Value
  50734. * @param property The property to transition
  50735. * @param targetValue The target Value of the property
  50736. * @param host The object where the property to animate belongs
  50737. * @param scene Scene used to run the animation
  50738. * @param frameRate Framerate (in frame/s) to use
  50739. * @param transition The transition type we want to use
  50740. * @param duration The duration of the animation, in milliseconds
  50741. * @param onAnimationEnd Callback trigger at the end of the animation
  50742. * @returns Nullable animation
  50743. */
  50744. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50745. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50746. if (duration <= 0) {
  50747. host[property] = targetValue;
  50748. if (onAnimationEnd) {
  50749. onAnimationEnd();
  50750. }
  50751. return null;
  50752. }
  50753. var endFrame = frameRate * (duration / 1000);
  50754. transition.setKeys([{
  50755. frame: 0,
  50756. value: host[property].clone ? host[property].clone() : host[property]
  50757. },
  50758. {
  50759. frame: endFrame,
  50760. value: targetValue
  50761. }]);
  50762. if (!host.animations) {
  50763. host.animations = [];
  50764. }
  50765. host.animations.push(transition);
  50766. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50767. animation.onAnimationEnd = onAnimationEnd;
  50768. return animation;
  50769. };
  50770. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50771. /**
  50772. * Return the array of runtime animations currently using this animation
  50773. */
  50774. get: function () {
  50775. return this._runtimeAnimations;
  50776. },
  50777. enumerable: true,
  50778. configurable: true
  50779. });
  50780. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50781. /**
  50782. * Specifies if any of the runtime animations are currently running
  50783. */
  50784. get: function () {
  50785. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50786. var runtimeAnimation = _a[_i];
  50787. if (!runtimeAnimation.isStopped) {
  50788. return true;
  50789. }
  50790. }
  50791. return false;
  50792. },
  50793. enumerable: true,
  50794. configurable: true
  50795. });
  50796. // Methods
  50797. /**
  50798. * Converts the animation to a string
  50799. * @param fullDetails support for multiple levels of logging within scene loading
  50800. * @returns String form of the animation
  50801. */
  50802. Animation.prototype.toString = function (fullDetails) {
  50803. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50804. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50805. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50806. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50807. if (fullDetails) {
  50808. ret += ", Ranges: {";
  50809. var first = true;
  50810. for (var name in this._ranges) {
  50811. if (first) {
  50812. ret += ", ";
  50813. first = false;
  50814. }
  50815. ret += name;
  50816. }
  50817. ret += "}";
  50818. }
  50819. return ret;
  50820. };
  50821. /**
  50822. * Add an event to this animation
  50823. * @param event Event to add
  50824. */
  50825. Animation.prototype.addEvent = function (event) {
  50826. this._events.push(event);
  50827. };
  50828. /**
  50829. * Remove all events found at the given frame
  50830. * @param frame The frame to remove events from
  50831. */
  50832. Animation.prototype.removeEvents = function (frame) {
  50833. for (var index = 0; index < this._events.length; index++) {
  50834. if (this._events[index].frame === frame) {
  50835. this._events.splice(index, 1);
  50836. index--;
  50837. }
  50838. }
  50839. };
  50840. /**
  50841. * Retrieves all the events from the animation
  50842. * @returns Events from the animation
  50843. */
  50844. Animation.prototype.getEvents = function () {
  50845. return this._events;
  50846. };
  50847. /**
  50848. * Creates an animation range
  50849. * @param name Name of the animation range
  50850. * @param from Starting frame of the animation range
  50851. * @param to Ending frame of the animation
  50852. */
  50853. Animation.prototype.createRange = function (name, from, to) {
  50854. // check name not already in use; could happen for bones after serialized
  50855. if (!this._ranges[name]) {
  50856. this._ranges[name] = new AnimationRange(name, from, to);
  50857. }
  50858. };
  50859. /**
  50860. * Deletes an animation range by name
  50861. * @param name Name of the animation range to delete
  50862. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50863. */
  50864. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50865. if (deleteFrames === void 0) { deleteFrames = true; }
  50866. var range = this._ranges[name];
  50867. if (!range) {
  50868. return;
  50869. }
  50870. if (deleteFrames) {
  50871. var from = range.from;
  50872. var to = range.to;
  50873. // this loop MUST go high to low for multiple splices to work
  50874. for (var key = this._keys.length - 1; key >= 0; key--) {
  50875. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50876. this._keys.splice(key, 1);
  50877. }
  50878. }
  50879. }
  50880. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50881. };
  50882. /**
  50883. * Gets the animation range by name, or null if not defined
  50884. * @param name Name of the animation range
  50885. * @returns Nullable animation range
  50886. */
  50887. Animation.prototype.getRange = function (name) {
  50888. return this._ranges[name];
  50889. };
  50890. /**
  50891. * Gets the key frames from the animation
  50892. * @returns The key frames of the animation
  50893. */
  50894. Animation.prototype.getKeys = function () {
  50895. return this._keys;
  50896. };
  50897. /**
  50898. * Gets the highest frame rate of the animation
  50899. * @returns Highest frame rate of the animation
  50900. */
  50901. Animation.prototype.getHighestFrame = function () {
  50902. var ret = 0;
  50903. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50904. if (ret < this._keys[key].frame) {
  50905. ret = this._keys[key].frame;
  50906. }
  50907. }
  50908. return ret;
  50909. };
  50910. /**
  50911. * Gets the easing function of the animation
  50912. * @returns Easing function of the animation
  50913. */
  50914. Animation.prototype.getEasingFunction = function () {
  50915. return this._easingFunction;
  50916. };
  50917. /**
  50918. * Sets the easing function of the animation
  50919. * @param easingFunction A custom mathematical formula for animation
  50920. */
  50921. Animation.prototype.setEasingFunction = function (easingFunction) {
  50922. this._easingFunction = easingFunction;
  50923. };
  50924. /**
  50925. * Interpolates a scalar linearly
  50926. * @param startValue Start value of the animation curve
  50927. * @param endValue End value of the animation curve
  50928. * @param gradient Scalar amount to interpolate
  50929. * @returns Interpolated scalar value
  50930. */
  50931. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50932. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50933. };
  50934. /**
  50935. * Interpolates a scalar cubically
  50936. * @param startValue Start value of the animation curve
  50937. * @param outTangent End tangent of the animation
  50938. * @param endValue End value of the animation curve
  50939. * @param inTangent Start tangent of the animation curve
  50940. * @param gradient Scalar amount to interpolate
  50941. * @returns Interpolated scalar value
  50942. */
  50943. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50944. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50945. };
  50946. /**
  50947. * Interpolates a quaternion using a spherical linear interpolation
  50948. * @param startValue Start value of the animation curve
  50949. * @param endValue End value of the animation curve
  50950. * @param gradient Scalar amount to interpolate
  50951. * @returns Interpolated quaternion value
  50952. */
  50953. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50954. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50955. };
  50956. /**
  50957. * Interpolates a quaternion cubically
  50958. * @param startValue Start value of the animation curve
  50959. * @param outTangent End tangent of the animation curve
  50960. * @param endValue End value of the animation curve
  50961. * @param inTangent Start tangent of the animation curve
  50962. * @param gradient Scalar amount to interpolate
  50963. * @returns Interpolated quaternion value
  50964. */
  50965. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50966. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50967. };
  50968. /**
  50969. * Interpolates a Vector3 linearl
  50970. * @param startValue Start value of the animation curve
  50971. * @param endValue End value of the animation curve
  50972. * @param gradient Scalar amount to interpolate
  50973. * @returns Interpolated scalar value
  50974. */
  50975. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50976. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50977. };
  50978. /**
  50979. * Interpolates a Vector3 cubically
  50980. * @param startValue Start value of the animation curve
  50981. * @param outTangent End tangent of the animation
  50982. * @param endValue End value of the animation curve
  50983. * @param inTangent Start tangent of the animation curve
  50984. * @param gradient Scalar amount to interpolate
  50985. * @returns InterpolatedVector3 value
  50986. */
  50987. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50988. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50989. };
  50990. /**
  50991. * Interpolates a Vector2 linearly
  50992. * @param startValue Start value of the animation curve
  50993. * @param endValue End value of the animation curve
  50994. * @param gradient Scalar amount to interpolate
  50995. * @returns Interpolated Vector2 value
  50996. */
  50997. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50998. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50999. };
  51000. /**
  51001. * Interpolates a Vector2 cubically
  51002. * @param startValue Start value of the animation curve
  51003. * @param outTangent End tangent of the animation
  51004. * @param endValue End value of the animation curve
  51005. * @param inTangent Start tangent of the animation curve
  51006. * @param gradient Scalar amount to interpolate
  51007. * @returns Interpolated Vector2 value
  51008. */
  51009. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51010. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51011. };
  51012. /**
  51013. * Interpolates a size linearly
  51014. * @param startValue Start value of the animation curve
  51015. * @param endValue End value of the animation curve
  51016. * @param gradient Scalar amount to interpolate
  51017. * @returns Interpolated Size value
  51018. */
  51019. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51020. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51021. };
  51022. /**
  51023. * Interpolates a Color3 linearly
  51024. * @param startValue Start value of the animation curve
  51025. * @param endValue End value of the animation curve
  51026. * @param gradient Scalar amount to interpolate
  51027. * @returns Interpolated Color3 value
  51028. */
  51029. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51030. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51031. };
  51032. /**
  51033. * @hidden Internal use only
  51034. */
  51035. Animation.prototype._getKeyValue = function (value) {
  51036. if (typeof value === "function") {
  51037. return value();
  51038. }
  51039. return value;
  51040. };
  51041. /**
  51042. * @hidden Internal use only
  51043. */
  51044. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51045. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51046. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51047. }
  51048. var keys = this.getKeys();
  51049. // Try to get a hash to find the right key
  51050. 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));
  51051. if (keys[startKeyIndex].frame >= currentFrame) {
  51052. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51053. startKeyIndex--;
  51054. }
  51055. }
  51056. for (var key = startKeyIndex; key < keys.length; key++) {
  51057. var endKey = keys[key + 1];
  51058. if (endKey.frame >= currentFrame) {
  51059. var startKey = keys[key];
  51060. var startValue = this._getKeyValue(startKey.value);
  51061. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51062. return startValue;
  51063. }
  51064. var endValue = this._getKeyValue(endKey.value);
  51065. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51066. var frameDelta = endKey.frame - startKey.frame;
  51067. // gradient : percent of currentFrame between the frame inf and the frame sup
  51068. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51069. // check for easingFunction and correction of gradient
  51070. var easingFunction = this.getEasingFunction();
  51071. if (easingFunction != null) {
  51072. gradient = easingFunction.ease(gradient);
  51073. }
  51074. switch (this.dataType) {
  51075. // Float
  51076. case Animation.ANIMATIONTYPE_FLOAT:
  51077. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51078. switch (loopMode) {
  51079. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51080. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51081. return floatValue;
  51082. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51083. return offsetValue * repeatCount + floatValue;
  51084. }
  51085. break;
  51086. // Quaternion
  51087. case Animation.ANIMATIONTYPE_QUATERNION:
  51088. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51089. switch (loopMode) {
  51090. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51091. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51092. return quatValue;
  51093. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51094. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51095. }
  51096. return quatValue;
  51097. // Vector3
  51098. case Animation.ANIMATIONTYPE_VECTOR3:
  51099. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51100. switch (loopMode) {
  51101. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51102. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51103. return vec3Value;
  51104. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51105. return vec3Value.add(offsetValue.scale(repeatCount));
  51106. }
  51107. // Vector2
  51108. case Animation.ANIMATIONTYPE_VECTOR2:
  51109. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51110. switch (loopMode) {
  51111. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51112. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51113. return vec2Value;
  51114. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51115. return vec2Value.add(offsetValue.scale(repeatCount));
  51116. }
  51117. // Size
  51118. case Animation.ANIMATIONTYPE_SIZE:
  51119. switch (loopMode) {
  51120. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51121. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51122. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51123. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51124. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51125. }
  51126. // Color3
  51127. case Animation.ANIMATIONTYPE_COLOR3:
  51128. switch (loopMode) {
  51129. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51130. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51131. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51132. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51133. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51134. }
  51135. // Matrix
  51136. case Animation.ANIMATIONTYPE_MATRIX:
  51137. switch (loopMode) {
  51138. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51139. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51140. if (Animation.AllowMatricesInterpolation) {
  51141. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51142. }
  51143. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51144. return startValue;
  51145. }
  51146. default:
  51147. break;
  51148. }
  51149. break;
  51150. }
  51151. }
  51152. return this._getKeyValue(keys[keys.length - 1].value);
  51153. };
  51154. /**
  51155. * Defines the function to use to interpolate matrices
  51156. * @param startValue defines the start matrix
  51157. * @param endValue defines the end matrix
  51158. * @param gradient defines the gradient between both matrices
  51159. * @param result defines an optional target matrix where to store the interpolation
  51160. * @returns the interpolated matrix
  51161. */
  51162. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51163. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51164. if (result) {
  51165. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51166. return result;
  51167. }
  51168. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51169. }
  51170. if (result) {
  51171. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51172. return result;
  51173. }
  51174. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51175. };
  51176. /**
  51177. * Makes a copy of the animation
  51178. * @returns Cloned animation
  51179. */
  51180. Animation.prototype.clone = function () {
  51181. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51182. clone.enableBlending = this.enableBlending;
  51183. clone.blendingSpeed = this.blendingSpeed;
  51184. if (this._keys) {
  51185. clone.setKeys(this._keys);
  51186. }
  51187. if (this._ranges) {
  51188. clone._ranges = {};
  51189. for (var name in this._ranges) {
  51190. var range = this._ranges[name];
  51191. if (!range) {
  51192. continue;
  51193. }
  51194. clone._ranges[name] = range.clone();
  51195. }
  51196. }
  51197. return clone;
  51198. };
  51199. /**
  51200. * Sets the key frames of the animation
  51201. * @param values The animation key frames to set
  51202. */
  51203. Animation.prototype.setKeys = function (values) {
  51204. this._keys = values.slice(0);
  51205. };
  51206. /**
  51207. * Serializes the animation to an object
  51208. * @returns Serialized object
  51209. */
  51210. Animation.prototype.serialize = function () {
  51211. var serializationObject = {};
  51212. serializationObject.name = this.name;
  51213. serializationObject.property = this.targetProperty;
  51214. serializationObject.framePerSecond = this.framePerSecond;
  51215. serializationObject.dataType = this.dataType;
  51216. serializationObject.loopBehavior = this.loopMode;
  51217. serializationObject.enableBlending = this.enableBlending;
  51218. serializationObject.blendingSpeed = this.blendingSpeed;
  51219. var dataType = this.dataType;
  51220. serializationObject.keys = [];
  51221. var keys = this.getKeys();
  51222. for (var index = 0; index < keys.length; index++) {
  51223. var animationKey = keys[index];
  51224. var key = {};
  51225. key.frame = animationKey.frame;
  51226. switch (dataType) {
  51227. case Animation.ANIMATIONTYPE_FLOAT:
  51228. key.values = [animationKey.value];
  51229. break;
  51230. case Animation.ANIMATIONTYPE_QUATERNION:
  51231. case Animation.ANIMATIONTYPE_MATRIX:
  51232. case Animation.ANIMATIONTYPE_VECTOR3:
  51233. case Animation.ANIMATIONTYPE_COLOR3:
  51234. key.values = animationKey.value.asArray();
  51235. break;
  51236. }
  51237. serializationObject.keys.push(key);
  51238. }
  51239. serializationObject.ranges = [];
  51240. for (var name in this._ranges) {
  51241. var source = this._ranges[name];
  51242. if (!source) {
  51243. continue;
  51244. }
  51245. var range = {};
  51246. range.name = name;
  51247. range.from = source.from;
  51248. range.to = source.to;
  51249. serializationObject.ranges.push(range);
  51250. }
  51251. return serializationObject;
  51252. };
  51253. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51254. /**
  51255. * Get the float animation type
  51256. */
  51257. get: function () {
  51258. return Animation._ANIMATIONTYPE_FLOAT;
  51259. },
  51260. enumerable: true,
  51261. configurable: true
  51262. });
  51263. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51264. /**
  51265. * Get the Vector3 animation type
  51266. */
  51267. get: function () {
  51268. return Animation._ANIMATIONTYPE_VECTOR3;
  51269. },
  51270. enumerable: true,
  51271. configurable: true
  51272. });
  51273. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51274. /**
  51275. * Get the Vectpr2 animation type
  51276. */
  51277. get: function () {
  51278. return Animation._ANIMATIONTYPE_VECTOR2;
  51279. },
  51280. enumerable: true,
  51281. configurable: true
  51282. });
  51283. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51284. /**
  51285. * Get the Size animation type
  51286. */
  51287. get: function () {
  51288. return Animation._ANIMATIONTYPE_SIZE;
  51289. },
  51290. enumerable: true,
  51291. configurable: true
  51292. });
  51293. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51294. /**
  51295. * Get the Quaternion animation type
  51296. */
  51297. get: function () {
  51298. return Animation._ANIMATIONTYPE_QUATERNION;
  51299. },
  51300. enumerable: true,
  51301. configurable: true
  51302. });
  51303. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51304. /**
  51305. * Get the Matrix animation type
  51306. */
  51307. get: function () {
  51308. return Animation._ANIMATIONTYPE_MATRIX;
  51309. },
  51310. enumerable: true,
  51311. configurable: true
  51312. });
  51313. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51314. /**
  51315. * Get the Color3 animation type
  51316. */
  51317. get: function () {
  51318. return Animation._ANIMATIONTYPE_COLOR3;
  51319. },
  51320. enumerable: true,
  51321. configurable: true
  51322. });
  51323. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51324. /**
  51325. * Get the Relative Loop Mode
  51326. */
  51327. get: function () {
  51328. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51329. },
  51330. enumerable: true,
  51331. configurable: true
  51332. });
  51333. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51334. /**
  51335. * Get the Cycle Loop Mode
  51336. */
  51337. get: function () {
  51338. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51339. },
  51340. enumerable: true,
  51341. configurable: true
  51342. });
  51343. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51344. /**
  51345. * Get the Constant Loop Mode
  51346. */
  51347. get: function () {
  51348. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51349. },
  51350. enumerable: true,
  51351. configurable: true
  51352. });
  51353. /** @hidden */
  51354. Animation._UniversalLerp = function (left, right, amount) {
  51355. var constructor = left.constructor;
  51356. if (constructor.Lerp) { // Lerp supported
  51357. return constructor.Lerp(left, right, amount);
  51358. }
  51359. else if (constructor.Slerp) { // Slerp supported
  51360. return constructor.Slerp(left, right, amount);
  51361. }
  51362. else if (left.toFixed) { // Number
  51363. return left * (1.0 - amount) + amount * right;
  51364. }
  51365. else { // Blending not supported
  51366. return right;
  51367. }
  51368. };
  51369. /**
  51370. * Parses an animation object and creates an animation
  51371. * @param parsedAnimation Parsed animation object
  51372. * @returns Animation object
  51373. */
  51374. Animation.Parse = function (parsedAnimation) {
  51375. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51376. var dataType = parsedAnimation.dataType;
  51377. var keys = [];
  51378. var data;
  51379. var index;
  51380. if (parsedAnimation.enableBlending) {
  51381. animation.enableBlending = parsedAnimation.enableBlending;
  51382. }
  51383. if (parsedAnimation.blendingSpeed) {
  51384. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51385. }
  51386. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51387. var key = parsedAnimation.keys[index];
  51388. var inTangent;
  51389. var outTangent;
  51390. switch (dataType) {
  51391. case Animation.ANIMATIONTYPE_FLOAT:
  51392. data = key.values[0];
  51393. if (key.values.length >= 1) {
  51394. inTangent = key.values[1];
  51395. }
  51396. if (key.values.length >= 2) {
  51397. outTangent = key.values[2];
  51398. }
  51399. break;
  51400. case Animation.ANIMATIONTYPE_QUATERNION:
  51401. data = BABYLON.Quaternion.FromArray(key.values);
  51402. if (key.values.length >= 8) {
  51403. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51404. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51405. inTangent = _inTangent;
  51406. }
  51407. }
  51408. if (key.values.length >= 12) {
  51409. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51410. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51411. outTangent = _outTangent;
  51412. }
  51413. }
  51414. break;
  51415. case Animation.ANIMATIONTYPE_MATRIX:
  51416. data = BABYLON.Matrix.FromArray(key.values);
  51417. break;
  51418. case Animation.ANIMATIONTYPE_COLOR3:
  51419. data = BABYLON.Color3.FromArray(key.values);
  51420. break;
  51421. case Animation.ANIMATIONTYPE_VECTOR3:
  51422. default:
  51423. data = BABYLON.Vector3.FromArray(key.values);
  51424. break;
  51425. }
  51426. var keyData = {};
  51427. keyData.frame = key.frame;
  51428. keyData.value = data;
  51429. if (inTangent != undefined) {
  51430. keyData.inTangent = inTangent;
  51431. }
  51432. if (outTangent != undefined) {
  51433. keyData.outTangent = outTangent;
  51434. }
  51435. keys.push(keyData);
  51436. }
  51437. animation.setKeys(keys);
  51438. if (parsedAnimation.ranges) {
  51439. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51440. data = parsedAnimation.ranges[index];
  51441. animation.createRange(data.name, data.from, data.to);
  51442. }
  51443. }
  51444. return animation;
  51445. };
  51446. /**
  51447. * Appends the serialized animations from the source animations
  51448. * @param source Source containing the animations
  51449. * @param destination Target to store the animations
  51450. */
  51451. Animation.AppendSerializedAnimations = function (source, destination) {
  51452. if (source.animations) {
  51453. destination.animations = [];
  51454. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51455. var animation = source.animations[animationIndex];
  51456. destination.animations.push(animation.serialize());
  51457. }
  51458. }
  51459. };
  51460. /**
  51461. * Use matrix interpolation instead of using direct key value when animating matrices
  51462. */
  51463. Animation.AllowMatricesInterpolation = false;
  51464. /**
  51465. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51466. */
  51467. Animation.AllowMatrixDecomposeForInterpolation = true;
  51468. // Statics
  51469. /**
  51470. * Float animation type
  51471. */
  51472. Animation._ANIMATIONTYPE_FLOAT = 0;
  51473. /**
  51474. * Vector3 animation type
  51475. */
  51476. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51477. /**
  51478. * Quaternion animation type
  51479. */
  51480. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51481. /**
  51482. * Matrix animation type
  51483. */
  51484. Animation._ANIMATIONTYPE_MATRIX = 3;
  51485. /**
  51486. * Color3 animation type
  51487. */
  51488. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51489. /**
  51490. * Vector2 animation type
  51491. */
  51492. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51493. /**
  51494. * Size animation type
  51495. */
  51496. Animation._ANIMATIONTYPE_SIZE = 6;
  51497. /**
  51498. * Relative Loop Mode
  51499. */
  51500. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51501. /**
  51502. * Cycle Loop Mode
  51503. */
  51504. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51505. /**
  51506. * Constant Loop Mode
  51507. */
  51508. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51509. return Animation;
  51510. }());
  51511. BABYLON.Animation = Animation;
  51512. })(BABYLON || (BABYLON = {}));
  51513. //# sourceMappingURL=babylon.animation.js.map
  51514. var BABYLON;
  51515. (function (BABYLON) {
  51516. /**
  51517. * This class defines the direct association between an animation and a target
  51518. */
  51519. var TargetedAnimation = /** @class */ (function () {
  51520. function TargetedAnimation() {
  51521. }
  51522. return TargetedAnimation;
  51523. }());
  51524. BABYLON.TargetedAnimation = TargetedAnimation;
  51525. /**
  51526. * Use this class to create coordinated animations on multiple targets
  51527. */
  51528. var AnimationGroup = /** @class */ (function () {
  51529. function AnimationGroup(name, scene) {
  51530. if (scene === void 0) { scene = null; }
  51531. this.name = name;
  51532. this._targetedAnimations = new Array();
  51533. this._animatables = new Array();
  51534. this._from = Number.MAX_VALUE;
  51535. this._to = -Number.MAX_VALUE;
  51536. this._speedRatio = 1;
  51537. this.onAnimationEndObservable = new BABYLON.Observable();
  51538. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51539. this._scene.animationGroups.push(this);
  51540. }
  51541. Object.defineProperty(AnimationGroup.prototype, "from", {
  51542. /**
  51543. * Gets the first frame
  51544. */
  51545. get: function () {
  51546. return this._from;
  51547. },
  51548. enumerable: true,
  51549. configurable: true
  51550. });
  51551. Object.defineProperty(AnimationGroup.prototype, "to", {
  51552. /**
  51553. * Gets the last frame
  51554. */
  51555. get: function () {
  51556. return this._to;
  51557. },
  51558. enumerable: true,
  51559. configurable: true
  51560. });
  51561. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51562. /**
  51563. * Define if the animations are started
  51564. */
  51565. get: function () {
  51566. return this._isStarted;
  51567. },
  51568. enumerable: true,
  51569. configurable: true
  51570. });
  51571. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51572. /**
  51573. * Gets or sets the speed ratio to use for all animations
  51574. */
  51575. get: function () {
  51576. return this._speedRatio;
  51577. },
  51578. /**
  51579. * Gets or sets the speed ratio to use for all animations
  51580. */
  51581. set: function (value) {
  51582. if (this._speedRatio === value) {
  51583. return;
  51584. }
  51585. this._speedRatio = value;
  51586. for (var index = 0; index < this._animatables.length; index++) {
  51587. var animatable = this._animatables[index];
  51588. animatable.speedRatio = this._speedRatio;
  51589. }
  51590. },
  51591. enumerable: true,
  51592. configurable: true
  51593. });
  51594. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51595. /**
  51596. * Gets the targeted animations for this animation group
  51597. */
  51598. get: function () {
  51599. return this._targetedAnimations;
  51600. },
  51601. enumerable: true,
  51602. configurable: true
  51603. });
  51604. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51605. /**
  51606. * returning the list of animatables controlled by this animation group.
  51607. */
  51608. get: function () {
  51609. return this._animatables;
  51610. },
  51611. enumerable: true,
  51612. configurable: true
  51613. });
  51614. /**
  51615. * Add an animation (with its target) in the group
  51616. * @param animation defines the animation we want to add
  51617. * @param target defines the target of the animation
  51618. * @returns the {BABYLON.TargetedAnimation} object
  51619. */
  51620. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51621. var targetedAnimation = {
  51622. animation: animation,
  51623. target: target
  51624. };
  51625. var keys = animation.getKeys();
  51626. if (this._from > keys[0].frame) {
  51627. this._from = keys[0].frame;
  51628. }
  51629. if (this._to < keys[keys.length - 1].frame) {
  51630. this._to = keys[keys.length - 1].frame;
  51631. }
  51632. this._targetedAnimations.push(targetedAnimation);
  51633. return targetedAnimation;
  51634. };
  51635. /**
  51636. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51637. * It can add constant keys at begin or end
  51638. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51639. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51640. */
  51641. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51642. if (beginFrame === void 0) { beginFrame = null; }
  51643. if (endFrame === void 0) { endFrame = null; }
  51644. if (beginFrame == null)
  51645. beginFrame = this._from;
  51646. if (endFrame == null)
  51647. endFrame = this._to;
  51648. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51649. var targetedAnimation = this._targetedAnimations[index];
  51650. var keys = targetedAnimation.animation.getKeys();
  51651. var startKey = keys[0];
  51652. var endKey = keys[keys.length - 1];
  51653. if (startKey.frame > beginFrame) {
  51654. var newKey = {
  51655. frame: beginFrame,
  51656. value: startKey.value,
  51657. inTangent: startKey.inTangent,
  51658. outTangent: startKey.outTangent,
  51659. interpolation: startKey.interpolation
  51660. };
  51661. keys.splice(0, 0, newKey);
  51662. }
  51663. if (endKey.frame < endFrame) {
  51664. var newKey = {
  51665. frame: endFrame,
  51666. value: endKey.value,
  51667. inTangent: endKey.outTangent,
  51668. outTangent: endKey.outTangent,
  51669. interpolation: endKey.interpolation
  51670. };
  51671. keys.push(newKey);
  51672. }
  51673. }
  51674. this._from = beginFrame;
  51675. this._to = endFrame;
  51676. return this;
  51677. };
  51678. /**
  51679. * Start all animations on given targets
  51680. * @param loop defines if animations must loop
  51681. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51682. * @param from defines the from key (optional)
  51683. * @param to defines the to key (optional)
  51684. * @returns the current animation group
  51685. */
  51686. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51687. var _this = this;
  51688. if (loop === void 0) { loop = false; }
  51689. if (speedRatio === void 0) { speedRatio = 1; }
  51690. if (this._isStarted || this._targetedAnimations.length === 0) {
  51691. return this;
  51692. }
  51693. var _loop_1 = function (targetedAnimation) {
  51694. 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 () {
  51695. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51696. }));
  51697. };
  51698. var this_1 = this;
  51699. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51700. var targetedAnimation = _a[_i];
  51701. _loop_1(targetedAnimation);
  51702. }
  51703. this._speedRatio = speedRatio;
  51704. this._isStarted = true;
  51705. return this;
  51706. };
  51707. /**
  51708. * Pause all animations
  51709. */
  51710. AnimationGroup.prototype.pause = function () {
  51711. if (!this._isStarted) {
  51712. return this;
  51713. }
  51714. for (var index = 0; index < this._animatables.length; index++) {
  51715. var animatable = this._animatables[index];
  51716. animatable.pause();
  51717. }
  51718. return this;
  51719. };
  51720. /**
  51721. * Play all animations to initial state
  51722. * This function will start() the animations if they were not started or will restart() them if they were paused
  51723. * @param loop defines if animations must loop
  51724. */
  51725. AnimationGroup.prototype.play = function (loop) {
  51726. if (this.isStarted) {
  51727. if (loop !== undefined) {
  51728. for (var index = 0; index < this._animatables.length; index++) {
  51729. var animatable = this._animatables[index];
  51730. animatable.loopAnimation = loop;
  51731. }
  51732. }
  51733. this.restart();
  51734. }
  51735. else {
  51736. this.start(loop, this._speedRatio);
  51737. }
  51738. return this;
  51739. };
  51740. /**
  51741. * Reset all animations to initial state
  51742. */
  51743. AnimationGroup.prototype.reset = function () {
  51744. if (!this._isStarted) {
  51745. return this;
  51746. }
  51747. for (var index = 0; index < this._animatables.length; index++) {
  51748. var animatable = this._animatables[index];
  51749. animatable.reset();
  51750. }
  51751. return this;
  51752. };
  51753. /**
  51754. * Restart animations from key 0
  51755. */
  51756. AnimationGroup.prototype.restart = function () {
  51757. if (!this._isStarted) {
  51758. return this;
  51759. }
  51760. for (var index = 0; index < this._animatables.length; index++) {
  51761. var animatable = this._animatables[index];
  51762. animatable.restart();
  51763. }
  51764. return this;
  51765. };
  51766. /**
  51767. * Stop all animations
  51768. */
  51769. AnimationGroup.prototype.stop = function () {
  51770. if (!this._isStarted) {
  51771. return this;
  51772. }
  51773. for (var index = 0; index < this._animatables.length; index++) {
  51774. var animatable = this._animatables[index];
  51775. animatable.stop();
  51776. }
  51777. this._isStarted = false;
  51778. return this;
  51779. };
  51780. /**
  51781. * Set animation weight for all animatables
  51782. * @param weight defines the weight to use
  51783. * @return the animationGroup
  51784. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51785. */
  51786. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51787. for (var index = 0; index < this._animatables.length; index++) {
  51788. var animatable = this._animatables[index];
  51789. animatable.weight = weight;
  51790. }
  51791. return this;
  51792. };
  51793. /**
  51794. * Synchronize and normalize all animatables with a source animatable
  51795. * @param root defines the root animatable to synchronize with
  51796. * @return the animationGroup
  51797. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51798. */
  51799. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51800. for (var index = 0; index < this._animatables.length; index++) {
  51801. var animatable = this._animatables[index];
  51802. animatable.syncWith(root);
  51803. }
  51804. return this;
  51805. };
  51806. /**
  51807. * Goes to a specific frame in this animation group
  51808. * @param frame the frame number to go to
  51809. * @return the animationGroup
  51810. */
  51811. AnimationGroup.prototype.goToFrame = function (frame) {
  51812. if (!this._isStarted) {
  51813. return this;
  51814. }
  51815. for (var index = 0; index < this._animatables.length; index++) {
  51816. var animatable = this._animatables[index];
  51817. animatable.goToFrame(frame);
  51818. }
  51819. return this;
  51820. };
  51821. /**
  51822. * Dispose all associated resources
  51823. */
  51824. AnimationGroup.prototype.dispose = function () {
  51825. this._targetedAnimations = [];
  51826. this._animatables = [];
  51827. var index = this._scene.animationGroups.indexOf(this);
  51828. if (index > -1) {
  51829. this._scene.animationGroups.splice(index, 1);
  51830. }
  51831. };
  51832. return AnimationGroup;
  51833. }());
  51834. BABYLON.AnimationGroup = AnimationGroup;
  51835. })(BABYLON || (BABYLON = {}));
  51836. //# sourceMappingURL=babylon.animationGroup.js.map
  51837. var BABYLON;
  51838. (function (BABYLON) {
  51839. /**
  51840. * Defines a runtime animation
  51841. */
  51842. var RuntimeAnimation = /** @class */ (function () {
  51843. /**
  51844. * Create a new RuntimeAnimation object
  51845. * @param target defines the target of the animation
  51846. * @param animation defines the source animation object
  51847. * @param scene defines the hosting scene
  51848. * @param host defines the initiating Animatable
  51849. */
  51850. function RuntimeAnimation(target, animation, scene, host) {
  51851. var _this = this;
  51852. this._events = new Array();
  51853. /**
  51854. * The current frame of the runtime animation
  51855. */
  51856. this._currentFrame = 0;
  51857. /**
  51858. * The original value of the runtime animation
  51859. */
  51860. this._originalValue = new Array();
  51861. /**
  51862. * The offsets cache of the runtime animation
  51863. */
  51864. this._offsetsCache = {};
  51865. /**
  51866. * The high limits cache of the runtime animation
  51867. */
  51868. this._highLimitsCache = {};
  51869. /**
  51870. * Specifies if the runtime animation has been stopped
  51871. */
  51872. this._stopped = false;
  51873. /**
  51874. * The blending factor of the runtime animation
  51875. */
  51876. this._blendingFactor = 0;
  51877. /**
  51878. * The target path of the runtime animation
  51879. */
  51880. this._targetPath = "";
  51881. /**
  51882. * The weight of the runtime animation
  51883. */
  51884. this._weight = 1.0;
  51885. /**
  51886. * The ratio offset of the runtime animation
  51887. */
  51888. this._ratioOffset = 0;
  51889. /**
  51890. * The previous delay of the runtime animation
  51891. */
  51892. this._previousDelay = 0;
  51893. /**
  51894. * The previous ratio of the runtime animation
  51895. */
  51896. this._previousRatio = 0;
  51897. this._animation = animation;
  51898. this._target = target;
  51899. this._scene = scene;
  51900. this._host = host;
  51901. animation._runtimeAnimations.push(this);
  51902. // Cloning events locally
  51903. var events = animation.getEvents();
  51904. if (events && events.length > 0) {
  51905. events.forEach(function (e) {
  51906. _this._events.push(e._clone());
  51907. });
  51908. }
  51909. }
  51910. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51911. /**
  51912. * Gets the current frame of the runtime animation
  51913. */
  51914. get: function () {
  51915. return this._currentFrame;
  51916. },
  51917. enumerable: true,
  51918. configurable: true
  51919. });
  51920. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51921. /**
  51922. * Gets the weight of the runtime animation
  51923. */
  51924. get: function () {
  51925. return this._weight;
  51926. },
  51927. enumerable: true,
  51928. configurable: true
  51929. });
  51930. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51931. /**
  51932. * Gets the current value of the runtime animation
  51933. */
  51934. get: function () {
  51935. return this._currentValue;
  51936. },
  51937. enumerable: true,
  51938. configurable: true
  51939. });
  51940. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51941. /**
  51942. * Gets the target path of the runtime animation
  51943. */
  51944. get: function () {
  51945. return this._targetPath;
  51946. },
  51947. enumerable: true,
  51948. configurable: true
  51949. });
  51950. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51951. /**
  51952. * Gets the actual target of the runtime animation
  51953. */
  51954. get: function () {
  51955. return this._activeTarget;
  51956. },
  51957. enumerable: true,
  51958. configurable: true
  51959. });
  51960. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51961. /**
  51962. * Gets the animation from the runtime animation
  51963. */
  51964. get: function () {
  51965. return this._animation;
  51966. },
  51967. enumerable: true,
  51968. configurable: true
  51969. });
  51970. /**
  51971. * Resets the runtime animation to the beginning
  51972. * @param restoreOriginal defines whether to restore the target property to the original value
  51973. */
  51974. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51975. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51976. if (restoreOriginal) {
  51977. if (this._target instanceof Array) {
  51978. var index = 0;
  51979. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51980. var target = _a[_i];
  51981. if (this._originalValue[index] !== undefined) {
  51982. this._setValue(target, this._originalValue[index], -1);
  51983. }
  51984. index++;
  51985. }
  51986. }
  51987. else {
  51988. if (this._originalValue[0] !== undefined) {
  51989. this._setValue(this._target, this._originalValue[0], -1);
  51990. }
  51991. }
  51992. }
  51993. this._offsetsCache = {};
  51994. this._highLimitsCache = {};
  51995. this._currentFrame = 0;
  51996. this._blendingFactor = 0;
  51997. this._originalValue = new Array();
  51998. // Events
  51999. for (var index = 0; index < this._events.length; index++) {
  52000. this._events[index].isDone = false;
  52001. }
  52002. };
  52003. /**
  52004. * Specifies if the runtime animation is stopped
  52005. * @returns Boolean specifying if the runtime animation is stopped
  52006. */
  52007. RuntimeAnimation.prototype.isStopped = function () {
  52008. return this._stopped;
  52009. };
  52010. /**
  52011. * Disposes of the runtime animation
  52012. */
  52013. RuntimeAnimation.prototype.dispose = function () {
  52014. var index = this._animation.runtimeAnimations.indexOf(this);
  52015. if (index > -1) {
  52016. this._animation.runtimeAnimations.splice(index, 1);
  52017. }
  52018. };
  52019. /**
  52020. * Interpolates the animation from the current frame
  52021. * @param currentFrame The frame to interpolate the animation to
  52022. * @param repeatCount The number of times that the animation should loop
  52023. * @param loopMode The type of looping mode to use
  52024. * @param offsetValue Animation offset value
  52025. * @param highLimitValue The high limit value
  52026. * @returns The interpolated value
  52027. */
  52028. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52029. this._currentFrame = currentFrame;
  52030. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52031. this._workValue = BABYLON.Matrix.Zero();
  52032. }
  52033. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52034. };
  52035. /**
  52036. * Apply the interpolated value to the target
  52037. * @param currentValue defines the value computed by the animation
  52038. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52039. */
  52040. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52041. if (weight === void 0) { weight = 1.0; }
  52042. if (this._target instanceof Array) {
  52043. var index = 0;
  52044. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52045. var target = _a[_i];
  52046. this._setValue(target, currentValue, weight, index);
  52047. index++;
  52048. }
  52049. }
  52050. else {
  52051. this._setValue(this._target, currentValue, weight);
  52052. }
  52053. };
  52054. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52055. if (targetIndex === void 0) { targetIndex = 0; }
  52056. // Set value
  52057. var path;
  52058. var destination;
  52059. var targetPropertyPath = this._animation.targetPropertyPath;
  52060. if (targetPropertyPath.length > 1) {
  52061. var property = target[targetPropertyPath[0]];
  52062. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52063. property = property[targetPropertyPath[index]];
  52064. }
  52065. path = targetPropertyPath[targetPropertyPath.length - 1];
  52066. destination = property;
  52067. }
  52068. else {
  52069. path = targetPropertyPath[0];
  52070. destination = target;
  52071. }
  52072. this._targetPath = path;
  52073. this._activeTarget = destination;
  52074. this._weight = weight;
  52075. if (this._originalValue[targetIndex] === undefined) {
  52076. var originalValue = void 0;
  52077. if (destination.getRestPose && path === "_matrix") { // For bones
  52078. originalValue = destination.getRestPose();
  52079. }
  52080. else {
  52081. originalValue = destination[path];
  52082. }
  52083. if (originalValue && originalValue.clone) {
  52084. this._originalValue[targetIndex] = originalValue.clone();
  52085. }
  52086. else {
  52087. this._originalValue[targetIndex] = originalValue;
  52088. }
  52089. }
  52090. // Blending
  52091. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52092. if (enableBlending && this._blendingFactor <= 1.0) {
  52093. if (!this._originalBlendValue) {
  52094. var originalValue = destination[path];
  52095. if (originalValue.clone) {
  52096. this._originalBlendValue = originalValue.clone();
  52097. }
  52098. else {
  52099. this._originalBlendValue = originalValue;
  52100. }
  52101. }
  52102. if (this._originalBlendValue.m) { // Matrix
  52103. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52104. if (this._currentValue) {
  52105. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52106. }
  52107. else {
  52108. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52109. }
  52110. }
  52111. else {
  52112. if (this._currentValue) {
  52113. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52114. }
  52115. else {
  52116. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52117. }
  52118. }
  52119. }
  52120. else {
  52121. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52122. }
  52123. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52124. this._blendingFactor += blendingSpeed;
  52125. }
  52126. else {
  52127. this._currentValue = currentValue;
  52128. }
  52129. if (weight !== -1.0) {
  52130. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52131. }
  52132. else {
  52133. destination[path] = this._currentValue;
  52134. }
  52135. if (target.markAsDirty) {
  52136. target.markAsDirty(this._animation.targetProperty);
  52137. }
  52138. };
  52139. /**
  52140. * Gets the loop pmode of the runtime animation
  52141. * @returns Loop Mode
  52142. */
  52143. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52144. if (this._target && this._target.animationPropertiesOverride) {
  52145. return this._target.animationPropertiesOverride.loopMode;
  52146. }
  52147. return this._animation.loopMode;
  52148. };
  52149. /**
  52150. * Move the current animation to a given frame
  52151. * @param frame defines the frame to move to
  52152. */
  52153. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52154. var keys = this._animation.getKeys();
  52155. if (frame < keys[0].frame) {
  52156. frame = keys[0].frame;
  52157. }
  52158. else if (frame > keys[keys.length - 1].frame) {
  52159. frame = keys[keys.length - 1].frame;
  52160. }
  52161. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52162. this.setValue(currentValue, -1);
  52163. };
  52164. /**
  52165. * @hidden Internal use only
  52166. */
  52167. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52168. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52169. this._ratioOffset = this._previousRatio - newRatio;
  52170. };
  52171. /**
  52172. * Execute the current animation
  52173. * @param delay defines the delay to add to the current frame
  52174. * @param from defines the lower bound of the animation range
  52175. * @param to defines the upper bound of the animation range
  52176. * @param loop defines if the current animation must loop
  52177. * @param speedRatio defines the current speed ratio
  52178. * @param weight defines the weight of the animation (default is -1 so no weight)
  52179. * @returns a boolean indicating if the animation has ended
  52180. */
  52181. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52182. if (weight === void 0) { weight = -1.0; }
  52183. var targetPropertyPath = this._animation.targetPropertyPath;
  52184. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52185. this._stopped = true;
  52186. return false;
  52187. }
  52188. var returnValue = true;
  52189. var keys = this._animation.getKeys();
  52190. // Adding a start key at frame 0 if missing
  52191. if (keys[0].frame !== 0) {
  52192. var newKey = { frame: 0, value: keys[0].value };
  52193. keys.splice(0, 0, newKey);
  52194. }
  52195. // Check limits
  52196. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52197. from = keys[0].frame;
  52198. }
  52199. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52200. to = keys[keys.length - 1].frame;
  52201. }
  52202. //to and from cannot be the same key
  52203. if (from === to) {
  52204. if (from > keys[0].frame) {
  52205. from--;
  52206. }
  52207. else if (to < keys[keys.length - 1].frame) {
  52208. to++;
  52209. }
  52210. }
  52211. // Compute ratio
  52212. var range = to - from;
  52213. var offsetValue;
  52214. // ratio represents the frame delta between from and to
  52215. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52216. var highLimitValue = 0;
  52217. this._previousDelay = delay;
  52218. this._previousRatio = ratio;
  52219. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  52220. returnValue = false;
  52221. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52222. }
  52223. else {
  52224. // Get max value if required
  52225. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52226. var keyOffset = to.toString() + from.toString();
  52227. if (!this._offsetsCache[keyOffset]) {
  52228. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52229. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52230. switch (this._animation.dataType) {
  52231. // Float
  52232. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52233. this._offsetsCache[keyOffset] = toValue - fromValue;
  52234. break;
  52235. // Quaternion
  52236. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52237. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52238. break;
  52239. // Vector3
  52240. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52241. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52242. // Vector2
  52243. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52244. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52245. // Size
  52246. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52247. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52248. // Color3
  52249. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52250. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52251. default:
  52252. break;
  52253. }
  52254. this._highLimitsCache[keyOffset] = toValue;
  52255. }
  52256. highLimitValue = this._highLimitsCache[keyOffset];
  52257. offsetValue = this._offsetsCache[keyOffset];
  52258. }
  52259. }
  52260. if (offsetValue === undefined) {
  52261. switch (this._animation.dataType) {
  52262. // Float
  52263. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52264. offsetValue = 0;
  52265. break;
  52266. // Quaternion
  52267. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52268. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52269. break;
  52270. // Vector3
  52271. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52272. offsetValue = BABYLON.Vector3.Zero();
  52273. break;
  52274. // Vector2
  52275. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52276. offsetValue = BABYLON.Vector2.Zero();
  52277. break;
  52278. // Size
  52279. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52280. offsetValue = BABYLON.Size.Zero();
  52281. break;
  52282. // Color3
  52283. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52284. offsetValue = BABYLON.Color3.Black();
  52285. }
  52286. }
  52287. // Compute value
  52288. var repeatCount = (ratio / range) >> 0;
  52289. var currentFrame = returnValue ? from + ratio % range : to;
  52290. // Need to normalize?
  52291. if (this._host && this._host.syncRoot) {
  52292. var syncRoot = this._host.syncRoot;
  52293. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52294. currentFrame = from + (to - from) * hostNormalizedFrame;
  52295. }
  52296. // Reset events if looping
  52297. var events = this._events;
  52298. if (range > 0 && this.currentFrame > currentFrame ||
  52299. range < 0 && this.currentFrame < currentFrame) {
  52300. // Need to reset animation events
  52301. for (var index = 0; index < events.length; index++) {
  52302. if (!events[index].onlyOnce) {
  52303. // reset event, the animation is looping
  52304. events[index].isDone = false;
  52305. }
  52306. }
  52307. }
  52308. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52309. // Set value
  52310. this.setValue(currentValue, weight);
  52311. // Check events
  52312. for (var index = 0; index < events.length; index++) {
  52313. // Make sure current frame has passed event frame and that event frame is within the current range
  52314. // Also, handle both forward and reverse animations
  52315. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52316. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52317. var event = events[index];
  52318. if (!event.isDone) {
  52319. // If event should be done only once, remove it.
  52320. if (event.onlyOnce) {
  52321. events.splice(index, 1);
  52322. index--;
  52323. }
  52324. event.isDone = true;
  52325. event.action();
  52326. } // Don't do anything if the event has already be done.
  52327. }
  52328. }
  52329. if (!returnValue) {
  52330. this._stopped = true;
  52331. }
  52332. return returnValue;
  52333. };
  52334. return RuntimeAnimation;
  52335. }());
  52336. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52337. })(BABYLON || (BABYLON = {}));
  52338. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52339. var BABYLON;
  52340. (function (BABYLON) {
  52341. var Animatable = /** @class */ (function () {
  52342. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52343. if (fromFrame === void 0) { fromFrame = 0; }
  52344. if (toFrame === void 0) { toFrame = 100; }
  52345. if (loopAnimation === void 0) { loopAnimation = false; }
  52346. if (speedRatio === void 0) { speedRatio = 1.0; }
  52347. this.target = target;
  52348. this.fromFrame = fromFrame;
  52349. this.toFrame = toFrame;
  52350. this.loopAnimation = loopAnimation;
  52351. this.onAnimationEnd = onAnimationEnd;
  52352. this._localDelayOffset = null;
  52353. this._pausedDelay = null;
  52354. this._runtimeAnimations = new Array();
  52355. this._paused = false;
  52356. this._speedRatio = 1;
  52357. this._weight = -1.0;
  52358. this.animationStarted = false;
  52359. /**
  52360. * Observer raised when the animation ends
  52361. */
  52362. this.onAnimationEndObservable = new BABYLON.Observable();
  52363. this._scene = scene;
  52364. if (animations) {
  52365. this.appendAnimations(target, animations);
  52366. }
  52367. this._speedRatio = speedRatio;
  52368. scene._activeAnimatables.push(this);
  52369. }
  52370. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52371. /**
  52372. * Gets the root Animatable used to synchronize and normalize animations
  52373. */
  52374. get: function () {
  52375. return this._syncRoot;
  52376. },
  52377. enumerable: true,
  52378. configurable: true
  52379. });
  52380. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52381. /**
  52382. * Gets the current frame of the first RuntimeAnimation
  52383. * Used to synchronize Animatables
  52384. */
  52385. get: function () {
  52386. if (this._runtimeAnimations.length === 0) {
  52387. return 0;
  52388. }
  52389. return this._runtimeAnimations[0].currentFrame;
  52390. },
  52391. enumerable: true,
  52392. configurable: true
  52393. });
  52394. Object.defineProperty(Animatable.prototype, "weight", {
  52395. /**
  52396. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52397. */
  52398. get: function () {
  52399. return this._weight;
  52400. },
  52401. set: function (value) {
  52402. if (value === -1) { // -1 is ok and means no weight
  52403. this._weight = -1;
  52404. return;
  52405. }
  52406. // Else weight must be in [0, 1] range
  52407. this._weight = Math.min(Math.max(value, 0), 1.0);
  52408. },
  52409. enumerable: true,
  52410. configurable: true
  52411. });
  52412. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52413. /**
  52414. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52415. */
  52416. get: function () {
  52417. return this._speedRatio;
  52418. },
  52419. set: function (value) {
  52420. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52421. var animation = this._runtimeAnimations[index];
  52422. animation._prepareForSpeedRatioChange(value);
  52423. }
  52424. this._speedRatio = value;
  52425. },
  52426. enumerable: true,
  52427. configurable: true
  52428. });
  52429. // Methods
  52430. /**
  52431. * Synchronize and normalize current Animatable with a source Animatable
  52432. * This is useful when using animation weights and when animations are not of the same length
  52433. * @param root defines the root Animatable to synchronize with
  52434. * @returns the current Animatable
  52435. */
  52436. Animatable.prototype.syncWith = function (root) {
  52437. this._syncRoot = root;
  52438. if (root) {
  52439. // Make sure this animatable will animate after the root
  52440. var index = this._scene._activeAnimatables.indexOf(this);
  52441. if (index > -1) {
  52442. this._scene._activeAnimatables.splice(index, 1);
  52443. this._scene._activeAnimatables.push(this);
  52444. }
  52445. }
  52446. return this;
  52447. };
  52448. Animatable.prototype.getAnimations = function () {
  52449. return this._runtimeAnimations;
  52450. };
  52451. Animatable.prototype.appendAnimations = function (target, animations) {
  52452. for (var index = 0; index < animations.length; index++) {
  52453. var animation = animations[index];
  52454. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52455. }
  52456. };
  52457. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52458. var runtimeAnimations = this._runtimeAnimations;
  52459. for (var index = 0; index < runtimeAnimations.length; index++) {
  52460. if (runtimeAnimations[index].animation.targetProperty === property) {
  52461. return runtimeAnimations[index].animation;
  52462. }
  52463. }
  52464. return null;
  52465. };
  52466. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52467. var runtimeAnimations = this._runtimeAnimations;
  52468. for (var index = 0; index < runtimeAnimations.length; index++) {
  52469. if (runtimeAnimations[index].animation.targetProperty === property) {
  52470. return runtimeAnimations[index];
  52471. }
  52472. }
  52473. return null;
  52474. };
  52475. Animatable.prototype.reset = function () {
  52476. var runtimeAnimations = this._runtimeAnimations;
  52477. for (var index = 0; index < runtimeAnimations.length; index++) {
  52478. runtimeAnimations[index].reset(true);
  52479. }
  52480. this._localDelayOffset = null;
  52481. this._pausedDelay = null;
  52482. };
  52483. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52484. var runtimeAnimations = this._runtimeAnimations;
  52485. for (var index = 0; index < runtimeAnimations.length; index++) {
  52486. runtimeAnimations[index].animation.enableBlending = true;
  52487. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52488. }
  52489. };
  52490. Animatable.prototype.disableBlending = function () {
  52491. var runtimeAnimations = this._runtimeAnimations;
  52492. for (var index = 0; index < runtimeAnimations.length; index++) {
  52493. runtimeAnimations[index].animation.enableBlending = false;
  52494. }
  52495. };
  52496. Animatable.prototype.goToFrame = function (frame) {
  52497. var runtimeAnimations = this._runtimeAnimations;
  52498. if (runtimeAnimations[0]) {
  52499. var fps = runtimeAnimations[0].animation.framePerSecond;
  52500. var currentFrame = runtimeAnimations[0].currentFrame;
  52501. var adjustTime = frame - currentFrame;
  52502. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52503. if (this._localDelayOffset === null) {
  52504. this._localDelayOffset = 0;
  52505. }
  52506. this._localDelayOffset -= delay;
  52507. }
  52508. for (var index = 0; index < runtimeAnimations.length; index++) {
  52509. runtimeAnimations[index].goToFrame(frame);
  52510. }
  52511. };
  52512. Animatable.prototype.pause = function () {
  52513. if (this._paused) {
  52514. return;
  52515. }
  52516. this._paused = true;
  52517. };
  52518. Animatable.prototype.restart = function () {
  52519. this._paused = false;
  52520. };
  52521. Animatable.prototype._raiseOnAnimationEnd = function () {
  52522. if (this.onAnimationEnd) {
  52523. this.onAnimationEnd();
  52524. }
  52525. this.onAnimationEndObservable.notifyObservers(this);
  52526. };
  52527. Animatable.prototype.stop = function (animationName) {
  52528. if (animationName) {
  52529. var idx = this._scene._activeAnimatables.indexOf(this);
  52530. if (idx > -1) {
  52531. var runtimeAnimations = this._runtimeAnimations;
  52532. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52533. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52534. continue;
  52535. }
  52536. runtimeAnimations[index].dispose();
  52537. runtimeAnimations.splice(index, 1);
  52538. }
  52539. if (runtimeAnimations.length == 0) {
  52540. this._scene._activeAnimatables.splice(idx, 1);
  52541. this._raiseOnAnimationEnd();
  52542. }
  52543. }
  52544. }
  52545. else {
  52546. var index = this._scene._activeAnimatables.indexOf(this);
  52547. if (index > -1) {
  52548. this._scene._activeAnimatables.splice(index, 1);
  52549. var runtimeAnimations = this._runtimeAnimations;
  52550. for (var index = 0; index < runtimeAnimations.length; index++) {
  52551. runtimeAnimations[index].dispose();
  52552. }
  52553. this._raiseOnAnimationEnd();
  52554. }
  52555. }
  52556. };
  52557. /**
  52558. * Wait asynchronously for the animation to end
  52559. * @returns a promise which will be fullfilled when the animation ends
  52560. */
  52561. Animatable.prototype.waitAsync = function () {
  52562. var _this = this;
  52563. return new Promise(function (resolve, reject) {
  52564. _this.onAnimationEndObservable.add(function () {
  52565. resolve(_this);
  52566. }, undefined, undefined, _this, true);
  52567. });
  52568. };
  52569. /** @hidden */
  52570. Animatable.prototype._animate = function (delay) {
  52571. if (this._paused) {
  52572. this.animationStarted = false;
  52573. if (this._pausedDelay === null) {
  52574. this._pausedDelay = delay;
  52575. }
  52576. return true;
  52577. }
  52578. if (this._localDelayOffset === null) {
  52579. this._localDelayOffset = delay;
  52580. this._pausedDelay = null;
  52581. }
  52582. else if (this._pausedDelay !== null) {
  52583. this._localDelayOffset += delay - this._pausedDelay;
  52584. this._pausedDelay = null;
  52585. }
  52586. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52587. return true;
  52588. }
  52589. // Animating
  52590. var running = false;
  52591. var runtimeAnimations = this._runtimeAnimations;
  52592. var index;
  52593. for (index = 0; index < runtimeAnimations.length; index++) {
  52594. var animation = runtimeAnimations[index];
  52595. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52596. running = running || isRunning;
  52597. }
  52598. this.animationStarted = running;
  52599. if (!running) {
  52600. // Remove from active animatables
  52601. index = this._scene._activeAnimatables.indexOf(this);
  52602. this._scene._activeAnimatables.splice(index, 1);
  52603. // Dispose all runtime animations
  52604. for (index = 0; index < runtimeAnimations.length; index++) {
  52605. runtimeAnimations[index].dispose();
  52606. }
  52607. }
  52608. if (!running) {
  52609. this._raiseOnAnimationEnd();
  52610. this.onAnimationEnd = null;
  52611. this.onAnimationEndObservable.clear();
  52612. }
  52613. return running;
  52614. };
  52615. return Animatable;
  52616. }());
  52617. BABYLON.Animatable = Animatable;
  52618. })(BABYLON || (BABYLON = {}));
  52619. //# sourceMappingURL=babylon.animatable.js.map
  52620. var BABYLON;
  52621. (function (BABYLON) {
  52622. var EasingFunction = /** @class */ (function () {
  52623. function EasingFunction() {
  52624. // Properties
  52625. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52626. }
  52627. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52628. get: function () {
  52629. return EasingFunction._EASINGMODE_EASEIN;
  52630. },
  52631. enumerable: true,
  52632. configurable: true
  52633. });
  52634. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52635. get: function () {
  52636. return EasingFunction._EASINGMODE_EASEOUT;
  52637. },
  52638. enumerable: true,
  52639. configurable: true
  52640. });
  52641. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52642. get: function () {
  52643. return EasingFunction._EASINGMODE_EASEINOUT;
  52644. },
  52645. enumerable: true,
  52646. configurable: true
  52647. });
  52648. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52649. var n = Math.min(Math.max(easingMode, 0), 2);
  52650. this._easingMode = n;
  52651. };
  52652. EasingFunction.prototype.getEasingMode = function () {
  52653. return this._easingMode;
  52654. };
  52655. EasingFunction.prototype.easeInCore = function (gradient) {
  52656. throw new Error('You must implement this method');
  52657. };
  52658. EasingFunction.prototype.ease = function (gradient) {
  52659. switch (this._easingMode) {
  52660. case EasingFunction.EASINGMODE_EASEIN:
  52661. return this.easeInCore(gradient);
  52662. case EasingFunction.EASINGMODE_EASEOUT:
  52663. return (1 - this.easeInCore(1 - gradient));
  52664. }
  52665. if (gradient >= 0.5) {
  52666. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52667. }
  52668. return (this.easeInCore(gradient * 2) * 0.5);
  52669. };
  52670. //Statics
  52671. EasingFunction._EASINGMODE_EASEIN = 0;
  52672. EasingFunction._EASINGMODE_EASEOUT = 1;
  52673. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52674. return EasingFunction;
  52675. }());
  52676. BABYLON.EasingFunction = EasingFunction;
  52677. var CircleEase = /** @class */ (function (_super) {
  52678. __extends(CircleEase, _super);
  52679. function CircleEase() {
  52680. return _super !== null && _super.apply(this, arguments) || this;
  52681. }
  52682. CircleEase.prototype.easeInCore = function (gradient) {
  52683. gradient = Math.max(0, Math.min(1, gradient));
  52684. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52685. };
  52686. return CircleEase;
  52687. }(EasingFunction));
  52688. BABYLON.CircleEase = CircleEase;
  52689. var BackEase = /** @class */ (function (_super) {
  52690. __extends(BackEase, _super);
  52691. function BackEase(amplitude) {
  52692. if (amplitude === void 0) { amplitude = 1; }
  52693. var _this = _super.call(this) || this;
  52694. _this.amplitude = amplitude;
  52695. return _this;
  52696. }
  52697. BackEase.prototype.easeInCore = function (gradient) {
  52698. var num = Math.max(0, this.amplitude);
  52699. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52700. };
  52701. return BackEase;
  52702. }(EasingFunction));
  52703. BABYLON.BackEase = BackEase;
  52704. var BounceEase = /** @class */ (function (_super) {
  52705. __extends(BounceEase, _super);
  52706. function BounceEase(bounces, bounciness) {
  52707. if (bounces === void 0) { bounces = 3; }
  52708. if (bounciness === void 0) { bounciness = 2; }
  52709. var _this = _super.call(this) || this;
  52710. _this.bounces = bounces;
  52711. _this.bounciness = bounciness;
  52712. return _this;
  52713. }
  52714. BounceEase.prototype.easeInCore = function (gradient) {
  52715. var y = Math.max(0.0, this.bounces);
  52716. var bounciness = this.bounciness;
  52717. if (bounciness <= 1.0) {
  52718. bounciness = 1.001;
  52719. }
  52720. var num9 = Math.pow(bounciness, y);
  52721. var num5 = 1.0 - bounciness;
  52722. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52723. var num15 = gradient * num4;
  52724. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52725. var num3 = Math.floor(num65);
  52726. var num13 = num3 + 1.0;
  52727. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52728. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52729. var num7 = (num8 + num12) * 0.5;
  52730. var num6 = gradient - num7;
  52731. var num2 = num7 - num8;
  52732. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52733. };
  52734. return BounceEase;
  52735. }(EasingFunction));
  52736. BABYLON.BounceEase = BounceEase;
  52737. var CubicEase = /** @class */ (function (_super) {
  52738. __extends(CubicEase, _super);
  52739. function CubicEase() {
  52740. return _super !== null && _super.apply(this, arguments) || this;
  52741. }
  52742. CubicEase.prototype.easeInCore = function (gradient) {
  52743. return (gradient * gradient * gradient);
  52744. };
  52745. return CubicEase;
  52746. }(EasingFunction));
  52747. BABYLON.CubicEase = CubicEase;
  52748. var ElasticEase = /** @class */ (function (_super) {
  52749. __extends(ElasticEase, _super);
  52750. function ElasticEase(oscillations, springiness) {
  52751. if (oscillations === void 0) { oscillations = 3; }
  52752. if (springiness === void 0) { springiness = 3; }
  52753. var _this = _super.call(this) || this;
  52754. _this.oscillations = oscillations;
  52755. _this.springiness = springiness;
  52756. return _this;
  52757. }
  52758. ElasticEase.prototype.easeInCore = function (gradient) {
  52759. var num2;
  52760. var num3 = Math.max(0.0, this.oscillations);
  52761. var num = Math.max(0.0, this.springiness);
  52762. if (num == 0) {
  52763. num2 = gradient;
  52764. }
  52765. else {
  52766. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52767. }
  52768. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52769. };
  52770. return ElasticEase;
  52771. }(EasingFunction));
  52772. BABYLON.ElasticEase = ElasticEase;
  52773. var ExponentialEase = /** @class */ (function (_super) {
  52774. __extends(ExponentialEase, _super);
  52775. function ExponentialEase(exponent) {
  52776. if (exponent === void 0) { exponent = 2; }
  52777. var _this = _super.call(this) || this;
  52778. _this.exponent = exponent;
  52779. return _this;
  52780. }
  52781. ExponentialEase.prototype.easeInCore = function (gradient) {
  52782. if (this.exponent <= 0) {
  52783. return gradient;
  52784. }
  52785. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52786. };
  52787. return ExponentialEase;
  52788. }(EasingFunction));
  52789. BABYLON.ExponentialEase = ExponentialEase;
  52790. var PowerEase = /** @class */ (function (_super) {
  52791. __extends(PowerEase, _super);
  52792. function PowerEase(power) {
  52793. if (power === void 0) { power = 2; }
  52794. var _this = _super.call(this) || this;
  52795. _this.power = power;
  52796. return _this;
  52797. }
  52798. PowerEase.prototype.easeInCore = function (gradient) {
  52799. var y = Math.max(0.0, this.power);
  52800. return Math.pow(gradient, y);
  52801. };
  52802. return PowerEase;
  52803. }(EasingFunction));
  52804. BABYLON.PowerEase = PowerEase;
  52805. var QuadraticEase = /** @class */ (function (_super) {
  52806. __extends(QuadraticEase, _super);
  52807. function QuadraticEase() {
  52808. return _super !== null && _super.apply(this, arguments) || this;
  52809. }
  52810. QuadraticEase.prototype.easeInCore = function (gradient) {
  52811. return (gradient * gradient);
  52812. };
  52813. return QuadraticEase;
  52814. }(EasingFunction));
  52815. BABYLON.QuadraticEase = QuadraticEase;
  52816. var QuarticEase = /** @class */ (function (_super) {
  52817. __extends(QuarticEase, _super);
  52818. function QuarticEase() {
  52819. return _super !== null && _super.apply(this, arguments) || this;
  52820. }
  52821. QuarticEase.prototype.easeInCore = function (gradient) {
  52822. return (gradient * gradient * gradient * gradient);
  52823. };
  52824. return QuarticEase;
  52825. }(EasingFunction));
  52826. BABYLON.QuarticEase = QuarticEase;
  52827. var QuinticEase = /** @class */ (function (_super) {
  52828. __extends(QuinticEase, _super);
  52829. function QuinticEase() {
  52830. return _super !== null && _super.apply(this, arguments) || this;
  52831. }
  52832. QuinticEase.prototype.easeInCore = function (gradient) {
  52833. return (gradient * gradient * gradient * gradient * gradient);
  52834. };
  52835. return QuinticEase;
  52836. }(EasingFunction));
  52837. BABYLON.QuinticEase = QuinticEase;
  52838. var SineEase = /** @class */ (function (_super) {
  52839. __extends(SineEase, _super);
  52840. function SineEase() {
  52841. return _super !== null && _super.apply(this, arguments) || this;
  52842. }
  52843. SineEase.prototype.easeInCore = function (gradient) {
  52844. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52845. };
  52846. return SineEase;
  52847. }(EasingFunction));
  52848. BABYLON.SineEase = SineEase;
  52849. var BezierCurveEase = /** @class */ (function (_super) {
  52850. __extends(BezierCurveEase, _super);
  52851. function BezierCurveEase(x1, y1, x2, y2) {
  52852. if (x1 === void 0) { x1 = 0; }
  52853. if (y1 === void 0) { y1 = 0; }
  52854. if (x2 === void 0) { x2 = 1; }
  52855. if (y2 === void 0) { y2 = 1; }
  52856. var _this = _super.call(this) || this;
  52857. _this.x1 = x1;
  52858. _this.y1 = y1;
  52859. _this.x2 = x2;
  52860. _this.y2 = y2;
  52861. return _this;
  52862. }
  52863. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52864. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52865. };
  52866. return BezierCurveEase;
  52867. }(EasingFunction));
  52868. BABYLON.BezierCurveEase = BezierCurveEase;
  52869. })(BABYLON || (BABYLON = {}));
  52870. //# sourceMappingURL=babylon.easing.js.map
  52871. var BABYLON;
  52872. (function (BABYLON) {
  52873. /**
  52874. * A Condition applied to an Action
  52875. */
  52876. var Condition = /** @class */ (function () {
  52877. /**
  52878. * Creates a new Condition
  52879. * @param actionManager the manager of the action the condition is applied to
  52880. */
  52881. function Condition(actionManager) {
  52882. this._actionManager = actionManager;
  52883. }
  52884. /**
  52885. * Check if the current condition is valid
  52886. * @returns a boolean
  52887. */
  52888. Condition.prototype.isValid = function () {
  52889. return true;
  52890. };
  52891. /**
  52892. * Internal only
  52893. * @hidden
  52894. */
  52895. Condition.prototype._getProperty = function (propertyPath) {
  52896. return this._actionManager._getProperty(propertyPath);
  52897. };
  52898. /**
  52899. * Internal only
  52900. * @hidden
  52901. */
  52902. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52903. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52904. };
  52905. /**
  52906. * Serialize placeholder for child classes
  52907. * @returns the serialized object
  52908. */
  52909. Condition.prototype.serialize = function () {
  52910. };
  52911. /**
  52912. * Internal only
  52913. * @hidden
  52914. */
  52915. Condition.prototype._serialize = function (serializedCondition) {
  52916. return {
  52917. type: 2,
  52918. children: [],
  52919. name: serializedCondition.name,
  52920. properties: serializedCondition.properties
  52921. };
  52922. };
  52923. return Condition;
  52924. }());
  52925. BABYLON.Condition = Condition;
  52926. /**
  52927. * Defines specific conditional operators as extensions of Condition
  52928. */
  52929. var ValueCondition = /** @class */ (function (_super) {
  52930. __extends(ValueCondition, _super);
  52931. /**
  52932. * Creates a new ValueCondition
  52933. * @param actionManager manager for the action the condition applies to
  52934. * @param target for the action
  52935. * @param propertyPath path to specify the property of the target the conditional operator uses
  52936. * @param value the value compared by the conditional operator against the current value of the property
  52937. * @param operator the conditional operator, default ValueCondition.IsEqual
  52938. */
  52939. function ValueCondition(actionManager, target,
  52940. /** path to specify the property of the target the conditional operator uses */
  52941. propertyPath,
  52942. /** the value compared by the conditional operator against the current value of the property */
  52943. value,
  52944. /** the conditional operator, default ValueCondition.IsEqual */
  52945. operator) {
  52946. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52947. var _this = _super.call(this, actionManager) || this;
  52948. _this.propertyPath = propertyPath;
  52949. _this.value = value;
  52950. _this.operator = operator;
  52951. _this._target = target;
  52952. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52953. _this._property = _this._getProperty(_this.propertyPath);
  52954. return _this;
  52955. }
  52956. Object.defineProperty(ValueCondition, "IsEqual", {
  52957. /**
  52958. * returns the number for IsEqual
  52959. */
  52960. get: function () {
  52961. return ValueCondition._IsEqual;
  52962. },
  52963. enumerable: true,
  52964. configurable: true
  52965. });
  52966. Object.defineProperty(ValueCondition, "IsDifferent", {
  52967. /**
  52968. * Returns the number for IsDifferent
  52969. */
  52970. get: function () {
  52971. return ValueCondition._IsDifferent;
  52972. },
  52973. enumerable: true,
  52974. configurable: true
  52975. });
  52976. Object.defineProperty(ValueCondition, "IsGreater", {
  52977. /**
  52978. * Returns the number for IsGreater
  52979. */
  52980. get: function () {
  52981. return ValueCondition._IsGreater;
  52982. },
  52983. enumerable: true,
  52984. configurable: true
  52985. });
  52986. Object.defineProperty(ValueCondition, "IsLesser", {
  52987. /**
  52988. * Returns the number for IsLesser
  52989. */
  52990. get: function () {
  52991. return ValueCondition._IsLesser;
  52992. },
  52993. enumerable: true,
  52994. configurable: true
  52995. });
  52996. /**
  52997. * Compares the given value with the property value for the specified conditional operator
  52998. * @returns the result of the comparison
  52999. */
  53000. ValueCondition.prototype.isValid = function () {
  53001. switch (this.operator) {
  53002. case ValueCondition.IsGreater:
  53003. return this._effectiveTarget[this._property] > this.value;
  53004. case ValueCondition.IsLesser:
  53005. return this._effectiveTarget[this._property] < this.value;
  53006. case ValueCondition.IsEqual:
  53007. case ValueCondition.IsDifferent:
  53008. var check;
  53009. if (this.value.equals) {
  53010. check = this.value.equals(this._effectiveTarget[this._property]);
  53011. }
  53012. else {
  53013. check = this.value === this._effectiveTarget[this._property];
  53014. }
  53015. return this.operator === ValueCondition.IsEqual ? check : !check;
  53016. }
  53017. return false;
  53018. };
  53019. /**
  53020. * Serialize the ValueCondition into a JSON compatible object
  53021. * @returns serialization object
  53022. */
  53023. ValueCondition.prototype.serialize = function () {
  53024. return this._serialize({
  53025. name: "ValueCondition",
  53026. properties: [
  53027. BABYLON.Action._GetTargetProperty(this._target),
  53028. { name: "propertyPath", value: this.propertyPath },
  53029. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53030. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53031. ]
  53032. });
  53033. };
  53034. /**
  53035. * Gets the name of the conditional operator for the ValueCondition
  53036. * @param operator the conditional operator
  53037. * @returns the name
  53038. */
  53039. ValueCondition.GetOperatorName = function (operator) {
  53040. switch (operator) {
  53041. case ValueCondition._IsEqual: return "IsEqual";
  53042. case ValueCondition._IsDifferent: return "IsDifferent";
  53043. case ValueCondition._IsGreater: return "IsGreater";
  53044. case ValueCondition._IsLesser: return "IsLesser";
  53045. default: return "";
  53046. }
  53047. };
  53048. /**
  53049. * Internal only
  53050. * @hidden
  53051. */
  53052. ValueCondition._IsEqual = 0;
  53053. /**
  53054. * Internal only
  53055. * @hidden
  53056. */
  53057. ValueCondition._IsDifferent = 1;
  53058. /**
  53059. * Internal only
  53060. * @hidden
  53061. */
  53062. ValueCondition._IsGreater = 2;
  53063. /**
  53064. * Internal only
  53065. * @hidden
  53066. */
  53067. ValueCondition._IsLesser = 3;
  53068. return ValueCondition;
  53069. }(Condition));
  53070. BABYLON.ValueCondition = ValueCondition;
  53071. /**
  53072. * Defines a predicate condition as an extension of Condition
  53073. */
  53074. var PredicateCondition = /** @class */ (function (_super) {
  53075. __extends(PredicateCondition, _super);
  53076. /**
  53077. * Creates a new PredicateCondition
  53078. * @param actionManager manager for the action the condition applies to
  53079. * @param predicate defines the predicate function used to validate the condition
  53080. */
  53081. function PredicateCondition(actionManager,
  53082. /** defines the predicate function used to validate the condition */
  53083. predicate) {
  53084. var _this = _super.call(this, actionManager) || this;
  53085. _this.predicate = predicate;
  53086. return _this;
  53087. }
  53088. /**
  53089. * @returns the validity of the predicate condition
  53090. */
  53091. PredicateCondition.prototype.isValid = function () {
  53092. return this.predicate();
  53093. };
  53094. return PredicateCondition;
  53095. }(Condition));
  53096. BABYLON.PredicateCondition = PredicateCondition;
  53097. /**
  53098. * Defines a state condition as an extension of Condition
  53099. */
  53100. var StateCondition = /** @class */ (function (_super) {
  53101. __extends(StateCondition, _super);
  53102. /**
  53103. * Creates a new StateCondition
  53104. * @param actionManager manager for the action the condition applies to
  53105. * @param target of the condition
  53106. * @param value to compare with target state
  53107. */
  53108. function StateCondition(actionManager, target, value) {
  53109. var _this = _super.call(this, actionManager) || this;
  53110. _this.value = value;
  53111. _this._target = target;
  53112. return _this;
  53113. }
  53114. /**
  53115. * @returns the validity of the state
  53116. */
  53117. StateCondition.prototype.isValid = function () {
  53118. return this._target.state === this.value;
  53119. };
  53120. /**
  53121. * Serialize the StateCondition into a JSON compatible object
  53122. * @returns serialization object
  53123. */
  53124. StateCondition.prototype.serialize = function () {
  53125. return this._serialize({
  53126. name: "StateCondition",
  53127. properties: [
  53128. BABYLON.Action._GetTargetProperty(this._target),
  53129. { name: "value", value: this.value }
  53130. ]
  53131. });
  53132. };
  53133. return StateCondition;
  53134. }(Condition));
  53135. BABYLON.StateCondition = StateCondition;
  53136. })(BABYLON || (BABYLON = {}));
  53137. //# sourceMappingURL=babylon.condition.js.map
  53138. var BABYLON;
  53139. (function (BABYLON) {
  53140. /**
  53141. * The action to be carried out following a trigger
  53142. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53143. */
  53144. var Action = /** @class */ (function () {
  53145. /**
  53146. * Creates a new Action
  53147. * @param triggerOptions the trigger, with or without parameters, for the action
  53148. * @param condition an optional determinant of action
  53149. */
  53150. function Action(
  53151. /** the trigger, with or without parameters, for the action */
  53152. triggerOptions, condition) {
  53153. this.triggerOptions = triggerOptions;
  53154. /**
  53155. * An event triggered prior to action being executed.
  53156. */
  53157. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53158. if (triggerOptions.parameter) {
  53159. this.trigger = triggerOptions.trigger;
  53160. this._triggerParameter = triggerOptions.parameter;
  53161. }
  53162. else {
  53163. this.trigger = triggerOptions;
  53164. }
  53165. this._nextActiveAction = this;
  53166. this._condition = condition;
  53167. }
  53168. /**
  53169. * Internal only
  53170. * @hidden
  53171. */
  53172. Action.prototype._prepare = function () {
  53173. };
  53174. /**
  53175. * Gets the trigger parameters
  53176. * @returns the trigger parameters
  53177. */
  53178. Action.prototype.getTriggerParameter = function () {
  53179. return this._triggerParameter;
  53180. };
  53181. /**
  53182. * Internal only - executes current action event
  53183. * @hidden
  53184. */
  53185. Action.prototype._executeCurrent = function (evt) {
  53186. if (this._nextActiveAction._condition) {
  53187. var condition = this._nextActiveAction._condition;
  53188. var currentRenderId = this._actionManager.getScene().getRenderId();
  53189. // We cache the current evaluation for the current frame
  53190. if (condition._evaluationId === currentRenderId) {
  53191. if (!condition._currentResult) {
  53192. return;
  53193. }
  53194. }
  53195. else {
  53196. condition._evaluationId = currentRenderId;
  53197. if (!condition.isValid()) {
  53198. condition._currentResult = false;
  53199. return;
  53200. }
  53201. condition._currentResult = true;
  53202. }
  53203. }
  53204. this.onBeforeExecuteObservable.notifyObservers(this);
  53205. this._nextActiveAction.execute(evt);
  53206. this.skipToNextActiveAction();
  53207. };
  53208. /**
  53209. * Execute placeholder for child classes
  53210. * @param evt optional action event
  53211. */
  53212. Action.prototype.execute = function (evt) {
  53213. };
  53214. /**
  53215. * Skips to next active action
  53216. */
  53217. Action.prototype.skipToNextActiveAction = function () {
  53218. if (this._nextActiveAction._child) {
  53219. if (!this._nextActiveAction._child._actionManager) {
  53220. this._nextActiveAction._child._actionManager = this._actionManager;
  53221. }
  53222. this._nextActiveAction = this._nextActiveAction._child;
  53223. }
  53224. else {
  53225. this._nextActiveAction = this;
  53226. }
  53227. };
  53228. /**
  53229. * Adds action to chain of actions, may be a DoNothingAction
  53230. * @param action defines the next action to execute
  53231. * @returns The action passed in
  53232. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53233. */
  53234. Action.prototype.then = function (action) {
  53235. this._child = action;
  53236. action._actionManager = this._actionManager;
  53237. action._prepare();
  53238. return action;
  53239. };
  53240. /**
  53241. * Internal only
  53242. * @hidden
  53243. */
  53244. Action.prototype._getProperty = function (propertyPath) {
  53245. return this._actionManager._getProperty(propertyPath);
  53246. };
  53247. /**
  53248. * Internal only
  53249. * @hidden
  53250. */
  53251. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53252. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53253. };
  53254. /**
  53255. * Serialize placeholder for child classes
  53256. * @param parent of child
  53257. * @returns the serialized object
  53258. */
  53259. Action.prototype.serialize = function (parent) {
  53260. };
  53261. /**
  53262. * Internal only called by serialize
  53263. * @hidden
  53264. */
  53265. Action.prototype._serialize = function (serializedAction, parent) {
  53266. var serializationObject = {
  53267. type: 1,
  53268. children: [],
  53269. name: serializedAction.name,
  53270. properties: serializedAction.properties || []
  53271. };
  53272. // Serialize child
  53273. if (this._child) {
  53274. this._child.serialize(serializationObject);
  53275. }
  53276. // Check if "this" has a condition
  53277. if (this._condition) {
  53278. var serializedCondition = this._condition.serialize();
  53279. serializedCondition.children.push(serializationObject);
  53280. if (parent) {
  53281. parent.children.push(serializedCondition);
  53282. }
  53283. return serializedCondition;
  53284. }
  53285. if (parent) {
  53286. parent.children.push(serializationObject);
  53287. }
  53288. return serializationObject;
  53289. };
  53290. /**
  53291. * Internal only
  53292. * @hidden
  53293. */
  53294. Action._SerializeValueAsString = function (value) {
  53295. if (typeof value === "number") {
  53296. return value.toString();
  53297. }
  53298. if (typeof value === "boolean") {
  53299. return value ? "true" : "false";
  53300. }
  53301. if (value instanceof BABYLON.Vector2) {
  53302. return value.x + ", " + value.y;
  53303. }
  53304. if (value instanceof BABYLON.Vector3) {
  53305. return value.x + ", " + value.y + ", " + value.z;
  53306. }
  53307. if (value instanceof BABYLON.Color3) {
  53308. return value.r + ", " + value.g + ", " + value.b;
  53309. }
  53310. if (value instanceof BABYLON.Color4) {
  53311. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53312. }
  53313. return value; // string
  53314. };
  53315. /**
  53316. * Internal only
  53317. * @hidden
  53318. */
  53319. Action._GetTargetProperty = function (target) {
  53320. return {
  53321. name: "target",
  53322. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53323. : target instanceof BABYLON.Light ? "LightProperties"
  53324. : target instanceof BABYLON.Camera ? "CameraProperties"
  53325. : "SceneProperties",
  53326. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53327. };
  53328. };
  53329. return Action;
  53330. }());
  53331. BABYLON.Action = Action;
  53332. })(BABYLON || (BABYLON = {}));
  53333. //# sourceMappingURL=babylon.action.js.map
  53334. var BABYLON;
  53335. (function (BABYLON) {
  53336. /**
  53337. * ActionEvent is the event being sent when an action is triggered.
  53338. */
  53339. var ActionEvent = /** @class */ (function () {
  53340. /**
  53341. * Creates a new ActionEvent
  53342. * @param source The mesh or sprite that triggered the action
  53343. * @param pointerX The X mouse cursor position at the time of the event
  53344. * @param pointerY The Y mouse cursor position at the time of the event
  53345. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53346. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53347. * @param additionalData additional data for the event
  53348. */
  53349. function ActionEvent(
  53350. /** The mesh or sprite that triggered the action */
  53351. source,
  53352. /** The X mouse cursor position at the time of the event */
  53353. pointerX,
  53354. /** The Y mouse cursor position at the time of the event */
  53355. pointerY,
  53356. /** The mesh that is currently pointed at (can be null) */
  53357. meshUnderPointer,
  53358. /** the original (browser) event that triggered the ActionEvent */
  53359. sourceEvent,
  53360. /** additional data for the event */
  53361. additionalData) {
  53362. this.source = source;
  53363. this.pointerX = pointerX;
  53364. this.pointerY = pointerY;
  53365. this.meshUnderPointer = meshUnderPointer;
  53366. this.sourceEvent = sourceEvent;
  53367. this.additionalData = additionalData;
  53368. }
  53369. /**
  53370. * Helper function to auto-create an ActionEvent from a source mesh.
  53371. * @param source The source mesh that triggered the event
  53372. * @param evt The original (browser) event
  53373. * @param additionalData additional data for the event
  53374. * @returns the new ActionEvent
  53375. */
  53376. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53377. var scene = source.getScene();
  53378. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53379. };
  53380. /**
  53381. * Helper function to auto-create an ActionEvent from a source sprite
  53382. * @param source The source sprite that triggered the event
  53383. * @param scene Scene associated with the sprite
  53384. * @param evt The original (browser) event
  53385. * @param additionalData additional data for the event
  53386. * @returns the new ActionEvent
  53387. */
  53388. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53389. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53390. };
  53391. /**
  53392. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53393. * @param scene the scene where the event occurred
  53394. * @param evt The original (browser) event
  53395. * @returns the new ActionEvent
  53396. */
  53397. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53398. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53399. };
  53400. /**
  53401. * Helper function to auto-create an ActionEvent from a primitive
  53402. * @param prim defines the target primitive
  53403. * @param pointerPos defines the pointer position
  53404. * @param evt The original (browser) event
  53405. * @param additionalData additional data for the event
  53406. * @returns the new ActionEvent
  53407. */
  53408. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53409. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53410. };
  53411. return ActionEvent;
  53412. }());
  53413. BABYLON.ActionEvent = ActionEvent;
  53414. /**
  53415. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53416. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53417. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53418. */
  53419. var ActionManager = /** @class */ (function () {
  53420. /**
  53421. * Creates a new action manager
  53422. * @param scene defines the hosting scene
  53423. */
  53424. function ActionManager(scene) {
  53425. // Members
  53426. /** Gets the list of actions */
  53427. this.actions = new Array();
  53428. /** Gets the cursor to use when hovering items */
  53429. this.hoverCursor = '';
  53430. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53431. scene._actionManagers.push(this);
  53432. }
  53433. Object.defineProperty(ActionManager, "NothingTrigger", {
  53434. /**
  53435. * Nothing
  53436. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53437. */
  53438. get: function () {
  53439. return ActionManager._NothingTrigger;
  53440. },
  53441. enumerable: true,
  53442. configurable: true
  53443. });
  53444. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53445. /**
  53446. * On pick
  53447. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53448. */
  53449. get: function () {
  53450. return ActionManager._OnPickTrigger;
  53451. },
  53452. enumerable: true,
  53453. configurable: true
  53454. });
  53455. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53456. /**
  53457. * On left pick
  53458. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53459. */
  53460. get: function () {
  53461. return ActionManager._OnLeftPickTrigger;
  53462. },
  53463. enumerable: true,
  53464. configurable: true
  53465. });
  53466. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53467. /**
  53468. * On right pick
  53469. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53470. */
  53471. get: function () {
  53472. return ActionManager._OnRightPickTrigger;
  53473. },
  53474. enumerable: true,
  53475. configurable: true
  53476. });
  53477. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53478. /**
  53479. * On center pick
  53480. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53481. */
  53482. get: function () {
  53483. return ActionManager._OnCenterPickTrigger;
  53484. },
  53485. enumerable: true,
  53486. configurable: true
  53487. });
  53488. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53489. /**
  53490. * On pick down
  53491. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53492. */
  53493. get: function () {
  53494. return ActionManager._OnPickDownTrigger;
  53495. },
  53496. enumerable: true,
  53497. configurable: true
  53498. });
  53499. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53500. /**
  53501. * On double pick
  53502. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53503. */
  53504. get: function () {
  53505. return ActionManager._OnDoublePickTrigger;
  53506. },
  53507. enumerable: true,
  53508. configurable: true
  53509. });
  53510. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53511. /**
  53512. * On pick up
  53513. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53514. */
  53515. get: function () {
  53516. return ActionManager._OnPickUpTrigger;
  53517. },
  53518. enumerable: true,
  53519. configurable: true
  53520. });
  53521. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53522. /**
  53523. * On pick out.
  53524. * This trigger will only be raised if you also declared a OnPickDown
  53525. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53526. */
  53527. get: function () {
  53528. return ActionManager._OnPickOutTrigger;
  53529. },
  53530. enumerable: true,
  53531. configurable: true
  53532. });
  53533. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53534. /**
  53535. * On long press
  53536. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53537. */
  53538. get: function () {
  53539. return ActionManager._OnLongPressTrigger;
  53540. },
  53541. enumerable: true,
  53542. configurable: true
  53543. });
  53544. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53545. /**
  53546. * On pointer over
  53547. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53548. */
  53549. get: function () {
  53550. return ActionManager._OnPointerOverTrigger;
  53551. },
  53552. enumerable: true,
  53553. configurable: true
  53554. });
  53555. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53556. /**
  53557. * On pointer out
  53558. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53559. */
  53560. get: function () {
  53561. return ActionManager._OnPointerOutTrigger;
  53562. },
  53563. enumerable: true,
  53564. configurable: true
  53565. });
  53566. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53567. /**
  53568. * On every frame
  53569. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53570. */
  53571. get: function () {
  53572. return ActionManager._OnEveryFrameTrigger;
  53573. },
  53574. enumerable: true,
  53575. configurable: true
  53576. });
  53577. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53578. /**
  53579. * On intersection enter
  53580. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53581. */
  53582. get: function () {
  53583. return ActionManager._OnIntersectionEnterTrigger;
  53584. },
  53585. enumerable: true,
  53586. configurable: true
  53587. });
  53588. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53589. /**
  53590. * On intersection exit
  53591. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53592. */
  53593. get: function () {
  53594. return ActionManager._OnIntersectionExitTrigger;
  53595. },
  53596. enumerable: true,
  53597. configurable: true
  53598. });
  53599. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53600. /**
  53601. * On key down
  53602. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53603. */
  53604. get: function () {
  53605. return ActionManager._OnKeyDownTrigger;
  53606. },
  53607. enumerable: true,
  53608. configurable: true
  53609. });
  53610. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53611. /**
  53612. * On key up
  53613. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53614. */
  53615. get: function () {
  53616. return ActionManager._OnKeyUpTrigger;
  53617. },
  53618. enumerable: true,
  53619. configurable: true
  53620. });
  53621. // Methods
  53622. /**
  53623. * Releases all associated resources
  53624. */
  53625. ActionManager.prototype.dispose = function () {
  53626. var index = this._scene._actionManagers.indexOf(this);
  53627. for (var i = 0; i < this.actions.length; i++) {
  53628. var action = this.actions[i];
  53629. ActionManager.Triggers[action.trigger]--;
  53630. if (ActionManager.Triggers[action.trigger] === 0) {
  53631. delete ActionManager.Triggers[action.trigger];
  53632. }
  53633. }
  53634. if (index > -1) {
  53635. this._scene._actionManagers.splice(index, 1);
  53636. }
  53637. };
  53638. /**
  53639. * Gets hosting scene
  53640. * @returns the hosting scene
  53641. */
  53642. ActionManager.prototype.getScene = function () {
  53643. return this._scene;
  53644. };
  53645. /**
  53646. * Does this action manager handles actions of any of the given triggers
  53647. * @param triggers defines the triggers to be tested
  53648. * @return a boolean indicating whether one (or more) of the triggers is handled
  53649. */
  53650. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53651. for (var index = 0; index < this.actions.length; index++) {
  53652. var action = this.actions[index];
  53653. if (triggers.indexOf(action.trigger) > -1) {
  53654. return true;
  53655. }
  53656. }
  53657. return false;
  53658. };
  53659. /**
  53660. * Does this action manager handles actions of a given trigger
  53661. * @param trigger defines the trigger to be tested
  53662. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53663. * @return whether the trigger is handled
  53664. */
  53665. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53666. for (var index = 0; index < this.actions.length; index++) {
  53667. var action = this.actions[index];
  53668. if (action.trigger === trigger) {
  53669. if (parameterPredicate) {
  53670. if (parameterPredicate(action.getTriggerParameter())) {
  53671. return true;
  53672. }
  53673. }
  53674. else {
  53675. return true;
  53676. }
  53677. }
  53678. }
  53679. return false;
  53680. };
  53681. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53682. /**
  53683. * Does this action manager has pointer triggers
  53684. */
  53685. get: function () {
  53686. for (var index = 0; index < this.actions.length; index++) {
  53687. var action = this.actions[index];
  53688. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53689. return true;
  53690. }
  53691. }
  53692. return false;
  53693. },
  53694. enumerable: true,
  53695. configurable: true
  53696. });
  53697. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53698. /**
  53699. * Does this action manager has pick triggers
  53700. */
  53701. get: function () {
  53702. for (var index = 0; index < this.actions.length; index++) {
  53703. var action = this.actions[index];
  53704. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53705. return true;
  53706. }
  53707. }
  53708. return false;
  53709. },
  53710. enumerable: true,
  53711. configurable: true
  53712. });
  53713. Object.defineProperty(ActionManager, "HasTriggers", {
  53714. /**
  53715. * Does exist one action manager with at least one trigger
  53716. **/
  53717. get: function () {
  53718. for (var t in ActionManager.Triggers) {
  53719. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53720. return true;
  53721. }
  53722. }
  53723. return false;
  53724. },
  53725. enumerable: true,
  53726. configurable: true
  53727. });
  53728. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53729. /**
  53730. * Does exist one action manager with at least one pick trigger
  53731. **/
  53732. get: function () {
  53733. for (var t in ActionManager.Triggers) {
  53734. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53735. var t_int = parseInt(t);
  53736. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53737. return true;
  53738. }
  53739. }
  53740. }
  53741. return false;
  53742. },
  53743. enumerable: true,
  53744. configurable: true
  53745. });
  53746. /**
  53747. * Does exist one action manager that handles actions of a given trigger
  53748. * @param trigger defines the trigger to be tested
  53749. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53750. **/
  53751. ActionManager.HasSpecificTrigger = function (trigger) {
  53752. for (var t in ActionManager.Triggers) {
  53753. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53754. var t_int = parseInt(t);
  53755. if (t_int === trigger) {
  53756. return true;
  53757. }
  53758. }
  53759. }
  53760. return false;
  53761. };
  53762. /**
  53763. * Registers an action to this action manager
  53764. * @param action defines the action to be registered
  53765. * @return the action amended (prepared) after registration
  53766. */
  53767. ActionManager.prototype.registerAction = function (action) {
  53768. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53769. if (this.getScene().actionManager !== this) {
  53770. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53771. return null;
  53772. }
  53773. }
  53774. this.actions.push(action);
  53775. if (ActionManager.Triggers[action.trigger]) {
  53776. ActionManager.Triggers[action.trigger]++;
  53777. }
  53778. else {
  53779. ActionManager.Triggers[action.trigger] = 1;
  53780. }
  53781. action._actionManager = this;
  53782. action._prepare();
  53783. return action;
  53784. };
  53785. /**
  53786. * Unregisters an action to this action manager
  53787. * @param action defines the action to be unregistered
  53788. * @return a boolean indicating whether the action has been unregistered
  53789. */
  53790. ActionManager.prototype.unregisterAction = function (action) {
  53791. var index = this.actions.indexOf(action);
  53792. if (index !== -1) {
  53793. this.actions.splice(index, 1);
  53794. ActionManager.Triggers[action.trigger] -= 1;
  53795. if (ActionManager.Triggers[action.trigger] === 0) {
  53796. delete ActionManager.Triggers[action.trigger];
  53797. }
  53798. delete action._actionManager;
  53799. return true;
  53800. }
  53801. return false;
  53802. };
  53803. /**
  53804. * Process a specific trigger
  53805. * @param trigger defines the trigger to process
  53806. * @param evt defines the event details to be processed
  53807. */
  53808. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53809. for (var index = 0; index < this.actions.length; index++) {
  53810. var action = this.actions[index];
  53811. if (action.trigger === trigger) {
  53812. if (evt) {
  53813. if (trigger === ActionManager.OnKeyUpTrigger
  53814. || trigger === ActionManager.OnKeyDownTrigger) {
  53815. var parameter = action.getTriggerParameter();
  53816. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53817. if (!parameter.toLowerCase) {
  53818. continue;
  53819. }
  53820. var lowerCase = parameter.toLowerCase();
  53821. if (lowerCase !== evt.sourceEvent.key) {
  53822. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53823. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53824. if (actualkey !== lowerCase) {
  53825. continue;
  53826. }
  53827. }
  53828. }
  53829. }
  53830. }
  53831. action._executeCurrent(evt);
  53832. }
  53833. }
  53834. };
  53835. /** @hidden */
  53836. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53837. var properties = propertyPath.split(".");
  53838. for (var index = 0; index < properties.length - 1; index++) {
  53839. target = target[properties[index]];
  53840. }
  53841. return target;
  53842. };
  53843. /** @hidden */
  53844. ActionManager.prototype._getProperty = function (propertyPath) {
  53845. var properties = propertyPath.split(".");
  53846. return properties[properties.length - 1];
  53847. };
  53848. /**
  53849. * Serialize this manager to a JSON object
  53850. * @param name defines the property name to store this manager
  53851. * @returns a JSON representation of this manager
  53852. */
  53853. ActionManager.prototype.serialize = function (name) {
  53854. var root = {
  53855. children: new Array(),
  53856. name: name,
  53857. type: 3,
  53858. properties: new Array() // Empty for root but required
  53859. };
  53860. for (var i = 0; i < this.actions.length; i++) {
  53861. var triggerObject = {
  53862. type: 0,
  53863. children: new Array(),
  53864. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53865. properties: new Array()
  53866. };
  53867. var triggerOptions = this.actions[i].triggerOptions;
  53868. if (triggerOptions && typeof triggerOptions !== "number") {
  53869. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53870. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53871. }
  53872. else {
  53873. var parameter = {};
  53874. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53875. if (triggerOptions.parameter.mesh) {
  53876. parameter._meshId = triggerOptions.parameter.mesh.id;
  53877. }
  53878. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53879. }
  53880. }
  53881. // Serialize child action, recursively
  53882. this.actions[i].serialize(triggerObject);
  53883. // Add serialized trigger
  53884. root.children.push(triggerObject);
  53885. }
  53886. return root;
  53887. };
  53888. /**
  53889. * Creates a new ActionManager from a JSON data
  53890. * @param parsedActions defines the JSON data to read from
  53891. * @param object defines the hosting mesh
  53892. * @param scene defines the hosting scene
  53893. */
  53894. ActionManager.Parse = function (parsedActions, object, scene) {
  53895. var actionManager = new ActionManager(scene);
  53896. if (object === null)
  53897. scene.actionManager = actionManager;
  53898. else
  53899. object.actionManager = actionManager;
  53900. // instanciate a new object
  53901. var instanciate = function (name, params) {
  53902. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53903. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53904. newInstance.constructor.apply(newInstance, params);
  53905. return newInstance;
  53906. };
  53907. var parseParameter = function (name, value, target, propertyPath) {
  53908. if (propertyPath === null) {
  53909. // String, boolean or float
  53910. var floatValue = parseFloat(value);
  53911. if (value === "true" || value === "false")
  53912. return value === "true";
  53913. else
  53914. return isNaN(floatValue) ? value : floatValue;
  53915. }
  53916. var effectiveTarget = propertyPath.split(".");
  53917. var values = value.split(",");
  53918. // Get effective Target
  53919. for (var i = 0; i < effectiveTarget.length; i++) {
  53920. target = target[effectiveTarget[i]];
  53921. }
  53922. // Return appropriate value with its type
  53923. if (typeof (target) === "boolean")
  53924. return values[0] === "true";
  53925. if (typeof (target) === "string")
  53926. return values[0];
  53927. // Parameters with multiple values such as Vector3 etc.
  53928. var split = new Array();
  53929. for (var i = 0; i < values.length; i++)
  53930. split.push(parseFloat(values[i]));
  53931. if (target instanceof BABYLON.Vector3)
  53932. return BABYLON.Vector3.FromArray(split);
  53933. if (target instanceof BABYLON.Vector4)
  53934. return BABYLON.Vector4.FromArray(split);
  53935. if (target instanceof BABYLON.Color3)
  53936. return BABYLON.Color3.FromArray(split);
  53937. if (target instanceof BABYLON.Color4)
  53938. return BABYLON.Color4.FromArray(split);
  53939. return parseFloat(values[0]);
  53940. };
  53941. // traverse graph per trigger
  53942. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53943. if (combineArray === void 0) { combineArray = null; }
  53944. if (parsedAction.detached)
  53945. return;
  53946. var parameters = new Array();
  53947. var target = null;
  53948. var propertyPath = null;
  53949. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53950. // Parameters
  53951. if (parsedAction.type === 2)
  53952. parameters.push(actionManager);
  53953. else
  53954. parameters.push(trigger);
  53955. if (combine) {
  53956. var actions = new Array();
  53957. for (var j = 0; j < parsedAction.combine.length; j++) {
  53958. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53959. }
  53960. parameters.push(actions);
  53961. }
  53962. else {
  53963. for (var i = 0; i < parsedAction.properties.length; i++) {
  53964. var value = parsedAction.properties[i].value;
  53965. var name = parsedAction.properties[i].name;
  53966. var targetType = parsedAction.properties[i].targetType;
  53967. if (name === "target")
  53968. if (targetType !== null && targetType === "SceneProperties")
  53969. value = target = scene;
  53970. else
  53971. value = target = scene.getNodeByName(value);
  53972. else if (name === "parent")
  53973. value = scene.getNodeByName(value);
  53974. else if (name === "sound")
  53975. value = scene.getSoundByName(value);
  53976. else if (name !== "propertyPath") {
  53977. if (parsedAction.type === 2 && name === "operator")
  53978. value = BABYLON.ValueCondition[value];
  53979. else
  53980. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53981. }
  53982. else {
  53983. propertyPath = value;
  53984. }
  53985. parameters.push(value);
  53986. }
  53987. }
  53988. if (combineArray === null) {
  53989. parameters.push(condition);
  53990. }
  53991. else {
  53992. parameters.push(null);
  53993. }
  53994. // If interpolate value action
  53995. if (parsedAction.name === "InterpolateValueAction") {
  53996. var param = parameters[parameters.length - 2];
  53997. parameters[parameters.length - 1] = param;
  53998. parameters[parameters.length - 2] = condition;
  53999. }
  54000. // Action or condition(s) and not CombineAction
  54001. var newAction = instanciate(parsedAction.name, parameters);
  54002. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54003. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54004. if (action)
  54005. action.then(nothing);
  54006. else
  54007. actionManager.registerAction(nothing);
  54008. action = nothing;
  54009. }
  54010. if (combineArray === null) {
  54011. if (newAction instanceof BABYLON.Condition) {
  54012. condition = newAction;
  54013. newAction = action;
  54014. }
  54015. else {
  54016. condition = null;
  54017. if (action)
  54018. action.then(newAction);
  54019. else
  54020. actionManager.registerAction(newAction);
  54021. }
  54022. }
  54023. else {
  54024. combineArray.push(newAction);
  54025. }
  54026. for (var i = 0; i < parsedAction.children.length; i++)
  54027. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54028. };
  54029. // triggers
  54030. for (var i = 0; i < parsedActions.children.length; i++) {
  54031. var triggerParams;
  54032. var trigger = parsedActions.children[i];
  54033. if (trigger.properties.length > 0) {
  54034. var param = trigger.properties[0].value;
  54035. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54036. if (value._meshId) {
  54037. value.mesh = scene.getMeshByID(value._meshId);
  54038. }
  54039. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54040. }
  54041. else
  54042. triggerParams = ActionManager[trigger.name];
  54043. for (var j = 0; j < trigger.children.length; j++) {
  54044. if (!trigger.detached)
  54045. traverse(trigger.children[j], triggerParams, null, null);
  54046. }
  54047. }
  54048. };
  54049. /**
  54050. * Get a trigger name by index
  54051. * @param trigger defines the trigger index
  54052. * @returns a trigger name
  54053. */
  54054. ActionManager.GetTriggerName = function (trigger) {
  54055. switch (trigger) {
  54056. case 0: return "NothingTrigger";
  54057. case 1: return "OnPickTrigger";
  54058. case 2: return "OnLeftPickTrigger";
  54059. case 3: return "OnRightPickTrigger";
  54060. case 4: return "OnCenterPickTrigger";
  54061. case 5: return "OnPickDownTrigger";
  54062. case 6: return "OnPickUpTrigger";
  54063. case 7: return "OnLongPressTrigger";
  54064. case 8: return "OnPointerOverTrigger";
  54065. case 9: return "OnPointerOutTrigger";
  54066. case 10: return "OnEveryFrameTrigger";
  54067. case 11: return "OnIntersectionEnterTrigger";
  54068. case 12: return "OnIntersectionExitTrigger";
  54069. case 13: return "OnKeyDownTrigger";
  54070. case 14: return "OnKeyUpTrigger";
  54071. case 15: return "OnPickOutTrigger";
  54072. default: return "";
  54073. }
  54074. };
  54075. // Statics
  54076. ActionManager._NothingTrigger = 0;
  54077. ActionManager._OnPickTrigger = 1;
  54078. ActionManager._OnLeftPickTrigger = 2;
  54079. ActionManager._OnRightPickTrigger = 3;
  54080. ActionManager._OnCenterPickTrigger = 4;
  54081. ActionManager._OnPickDownTrigger = 5;
  54082. ActionManager._OnDoublePickTrigger = 6;
  54083. ActionManager._OnPickUpTrigger = 7;
  54084. ActionManager._OnLongPressTrigger = 8;
  54085. ActionManager._OnPointerOverTrigger = 9;
  54086. ActionManager._OnPointerOutTrigger = 10;
  54087. ActionManager._OnEveryFrameTrigger = 11;
  54088. ActionManager._OnIntersectionEnterTrigger = 12;
  54089. ActionManager._OnIntersectionExitTrigger = 13;
  54090. ActionManager._OnKeyDownTrigger = 14;
  54091. ActionManager._OnKeyUpTrigger = 15;
  54092. ActionManager._OnPickOutTrigger = 16;
  54093. /** Gets the list of active triggers */
  54094. ActionManager.Triggers = {};
  54095. return ActionManager;
  54096. }());
  54097. BABYLON.ActionManager = ActionManager;
  54098. })(BABYLON || (BABYLON = {}));
  54099. //# sourceMappingURL=babylon.actionManager.js.map
  54100. var BABYLON;
  54101. (function (BABYLON) {
  54102. var InterpolateValueAction = /** @class */ (function (_super) {
  54103. __extends(InterpolateValueAction, _super);
  54104. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54105. if (duration === void 0) { duration = 1000; }
  54106. var _this = _super.call(this, triggerOptions, condition) || this;
  54107. _this.propertyPath = propertyPath;
  54108. _this.value = value;
  54109. _this.duration = duration;
  54110. _this.stopOtherAnimations = stopOtherAnimations;
  54111. _this.onInterpolationDone = onInterpolationDone;
  54112. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54113. _this._target = _this._effectiveTarget = target;
  54114. return _this;
  54115. }
  54116. InterpolateValueAction.prototype._prepare = function () {
  54117. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54118. this._property = this._getProperty(this.propertyPath);
  54119. };
  54120. InterpolateValueAction.prototype.execute = function () {
  54121. var _this = this;
  54122. var scene = this._actionManager.getScene();
  54123. var keys = [
  54124. {
  54125. frame: 0,
  54126. value: this._effectiveTarget[this._property]
  54127. }, {
  54128. frame: 100,
  54129. value: this.value
  54130. }
  54131. ];
  54132. var dataType;
  54133. if (typeof this.value === "number") {
  54134. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54135. }
  54136. else if (this.value instanceof BABYLON.Color3) {
  54137. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54138. }
  54139. else if (this.value instanceof BABYLON.Vector3) {
  54140. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54141. }
  54142. else if (this.value instanceof BABYLON.Matrix) {
  54143. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54144. }
  54145. else if (this.value instanceof BABYLON.Quaternion) {
  54146. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54147. }
  54148. else {
  54149. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54150. return;
  54151. }
  54152. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54153. animation.setKeys(keys);
  54154. if (this.stopOtherAnimations) {
  54155. scene.stopAnimation(this._effectiveTarget);
  54156. }
  54157. var wrapper = function () {
  54158. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54159. if (_this.onInterpolationDone) {
  54160. _this.onInterpolationDone();
  54161. }
  54162. };
  54163. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54164. };
  54165. InterpolateValueAction.prototype.serialize = function (parent) {
  54166. return _super.prototype._serialize.call(this, {
  54167. name: "InterpolateValueAction",
  54168. properties: [
  54169. BABYLON.Action._GetTargetProperty(this._target),
  54170. { name: "propertyPath", value: this.propertyPath },
  54171. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54172. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54173. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54174. ]
  54175. }, parent);
  54176. };
  54177. return InterpolateValueAction;
  54178. }(BABYLON.Action));
  54179. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54180. })(BABYLON || (BABYLON = {}));
  54181. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54182. var BABYLON;
  54183. (function (BABYLON) {
  54184. var SwitchBooleanAction = /** @class */ (function (_super) {
  54185. __extends(SwitchBooleanAction, _super);
  54186. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54187. var _this = _super.call(this, triggerOptions, condition) || this;
  54188. _this.propertyPath = propertyPath;
  54189. _this._target = _this._effectiveTarget = target;
  54190. return _this;
  54191. }
  54192. SwitchBooleanAction.prototype._prepare = function () {
  54193. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54194. this._property = this._getProperty(this.propertyPath);
  54195. };
  54196. SwitchBooleanAction.prototype.execute = function () {
  54197. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54198. };
  54199. SwitchBooleanAction.prototype.serialize = function (parent) {
  54200. return _super.prototype._serialize.call(this, {
  54201. name: "SwitchBooleanAction",
  54202. properties: [
  54203. BABYLON.Action._GetTargetProperty(this._target),
  54204. { name: "propertyPath", value: this.propertyPath }
  54205. ]
  54206. }, parent);
  54207. };
  54208. return SwitchBooleanAction;
  54209. }(BABYLON.Action));
  54210. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54211. var SetStateAction = /** @class */ (function (_super) {
  54212. __extends(SetStateAction, _super);
  54213. function SetStateAction(triggerOptions, target, value, condition) {
  54214. var _this = _super.call(this, triggerOptions, condition) || this;
  54215. _this.value = value;
  54216. _this._target = target;
  54217. return _this;
  54218. }
  54219. SetStateAction.prototype.execute = function () {
  54220. this._target.state = this.value;
  54221. };
  54222. SetStateAction.prototype.serialize = function (parent) {
  54223. return _super.prototype._serialize.call(this, {
  54224. name: "SetStateAction",
  54225. properties: [
  54226. BABYLON.Action._GetTargetProperty(this._target),
  54227. { name: "value", value: this.value }
  54228. ]
  54229. }, parent);
  54230. };
  54231. return SetStateAction;
  54232. }(BABYLON.Action));
  54233. BABYLON.SetStateAction = SetStateAction;
  54234. var SetValueAction = /** @class */ (function (_super) {
  54235. __extends(SetValueAction, _super);
  54236. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54237. var _this = _super.call(this, triggerOptions, condition) || this;
  54238. _this.propertyPath = propertyPath;
  54239. _this.value = value;
  54240. _this._target = _this._effectiveTarget = target;
  54241. return _this;
  54242. }
  54243. SetValueAction.prototype._prepare = function () {
  54244. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54245. this._property = this._getProperty(this.propertyPath);
  54246. };
  54247. SetValueAction.prototype.execute = function () {
  54248. this._effectiveTarget[this._property] = this.value;
  54249. if (this._target.markAsDirty) {
  54250. this._target.markAsDirty(this._property);
  54251. }
  54252. };
  54253. SetValueAction.prototype.serialize = function (parent) {
  54254. return _super.prototype._serialize.call(this, {
  54255. name: "SetValueAction",
  54256. properties: [
  54257. BABYLON.Action._GetTargetProperty(this._target),
  54258. { name: "propertyPath", value: this.propertyPath },
  54259. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54260. ]
  54261. }, parent);
  54262. };
  54263. return SetValueAction;
  54264. }(BABYLON.Action));
  54265. BABYLON.SetValueAction = SetValueAction;
  54266. var IncrementValueAction = /** @class */ (function (_super) {
  54267. __extends(IncrementValueAction, _super);
  54268. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54269. var _this = _super.call(this, triggerOptions, condition) || this;
  54270. _this.propertyPath = propertyPath;
  54271. _this.value = value;
  54272. _this._target = _this._effectiveTarget = target;
  54273. return _this;
  54274. }
  54275. IncrementValueAction.prototype._prepare = function () {
  54276. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54277. this._property = this._getProperty(this.propertyPath);
  54278. if (typeof this._effectiveTarget[this._property] !== "number") {
  54279. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54280. }
  54281. };
  54282. IncrementValueAction.prototype.execute = function () {
  54283. this._effectiveTarget[this._property] += this.value;
  54284. if (this._target.markAsDirty) {
  54285. this._target.markAsDirty(this._property);
  54286. }
  54287. };
  54288. IncrementValueAction.prototype.serialize = function (parent) {
  54289. return _super.prototype._serialize.call(this, {
  54290. name: "IncrementValueAction",
  54291. properties: [
  54292. BABYLON.Action._GetTargetProperty(this._target),
  54293. { name: "propertyPath", value: this.propertyPath },
  54294. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54295. ]
  54296. }, parent);
  54297. };
  54298. return IncrementValueAction;
  54299. }(BABYLON.Action));
  54300. BABYLON.IncrementValueAction = IncrementValueAction;
  54301. var PlayAnimationAction = /** @class */ (function (_super) {
  54302. __extends(PlayAnimationAction, _super);
  54303. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54304. var _this = _super.call(this, triggerOptions, condition) || this;
  54305. _this.from = from;
  54306. _this.to = to;
  54307. _this.loop = loop;
  54308. _this._target = target;
  54309. return _this;
  54310. }
  54311. PlayAnimationAction.prototype._prepare = function () {
  54312. };
  54313. PlayAnimationAction.prototype.execute = function () {
  54314. var scene = this._actionManager.getScene();
  54315. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54316. };
  54317. PlayAnimationAction.prototype.serialize = function (parent) {
  54318. return _super.prototype._serialize.call(this, {
  54319. name: "PlayAnimationAction",
  54320. properties: [
  54321. BABYLON.Action._GetTargetProperty(this._target),
  54322. { name: "from", value: String(this.from) },
  54323. { name: "to", value: String(this.to) },
  54324. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54325. ]
  54326. }, parent);
  54327. };
  54328. return PlayAnimationAction;
  54329. }(BABYLON.Action));
  54330. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54331. var StopAnimationAction = /** @class */ (function (_super) {
  54332. __extends(StopAnimationAction, _super);
  54333. function StopAnimationAction(triggerOptions, target, condition) {
  54334. var _this = _super.call(this, triggerOptions, condition) || this;
  54335. _this._target = target;
  54336. return _this;
  54337. }
  54338. StopAnimationAction.prototype._prepare = function () {
  54339. };
  54340. StopAnimationAction.prototype.execute = function () {
  54341. var scene = this._actionManager.getScene();
  54342. scene.stopAnimation(this._target);
  54343. };
  54344. StopAnimationAction.prototype.serialize = function (parent) {
  54345. return _super.prototype._serialize.call(this, {
  54346. name: "StopAnimationAction",
  54347. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54348. }, parent);
  54349. };
  54350. return StopAnimationAction;
  54351. }(BABYLON.Action));
  54352. BABYLON.StopAnimationAction = StopAnimationAction;
  54353. var DoNothingAction = /** @class */ (function (_super) {
  54354. __extends(DoNothingAction, _super);
  54355. function DoNothingAction(triggerOptions, condition) {
  54356. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54357. return _super.call(this, triggerOptions, condition) || this;
  54358. }
  54359. DoNothingAction.prototype.execute = function () {
  54360. };
  54361. DoNothingAction.prototype.serialize = function (parent) {
  54362. return _super.prototype._serialize.call(this, {
  54363. name: "DoNothingAction",
  54364. properties: []
  54365. }, parent);
  54366. };
  54367. return DoNothingAction;
  54368. }(BABYLON.Action));
  54369. BABYLON.DoNothingAction = DoNothingAction;
  54370. var CombineAction = /** @class */ (function (_super) {
  54371. __extends(CombineAction, _super);
  54372. function CombineAction(triggerOptions, children, condition) {
  54373. var _this = _super.call(this, triggerOptions, condition) || this;
  54374. _this.children = children;
  54375. return _this;
  54376. }
  54377. CombineAction.prototype._prepare = function () {
  54378. for (var index = 0; index < this.children.length; index++) {
  54379. this.children[index]._actionManager = this._actionManager;
  54380. this.children[index]._prepare();
  54381. }
  54382. };
  54383. CombineAction.prototype.execute = function (evt) {
  54384. for (var index = 0; index < this.children.length; index++) {
  54385. this.children[index].execute(evt);
  54386. }
  54387. };
  54388. CombineAction.prototype.serialize = function (parent) {
  54389. var serializationObject = _super.prototype._serialize.call(this, {
  54390. name: "CombineAction",
  54391. properties: [],
  54392. combine: []
  54393. }, parent);
  54394. for (var i = 0; i < this.children.length; i++) {
  54395. serializationObject.combine.push(this.children[i].serialize(null));
  54396. }
  54397. return serializationObject;
  54398. };
  54399. return CombineAction;
  54400. }(BABYLON.Action));
  54401. BABYLON.CombineAction = CombineAction;
  54402. var ExecuteCodeAction = /** @class */ (function (_super) {
  54403. __extends(ExecuteCodeAction, _super);
  54404. function ExecuteCodeAction(triggerOptions, func, condition) {
  54405. var _this = _super.call(this, triggerOptions, condition) || this;
  54406. _this.func = func;
  54407. return _this;
  54408. }
  54409. ExecuteCodeAction.prototype.execute = function (evt) {
  54410. this.func(evt);
  54411. };
  54412. return ExecuteCodeAction;
  54413. }(BABYLON.Action));
  54414. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54415. var SetParentAction = /** @class */ (function (_super) {
  54416. __extends(SetParentAction, _super);
  54417. function SetParentAction(triggerOptions, target, parent, condition) {
  54418. var _this = _super.call(this, triggerOptions, condition) || this;
  54419. _this._target = target;
  54420. _this._parent = parent;
  54421. return _this;
  54422. }
  54423. SetParentAction.prototype._prepare = function () {
  54424. };
  54425. SetParentAction.prototype.execute = function () {
  54426. if (this._target.parent === this._parent) {
  54427. return;
  54428. }
  54429. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54430. invertParentWorldMatrix.invert();
  54431. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54432. this._target.parent = this._parent;
  54433. };
  54434. SetParentAction.prototype.serialize = function (parent) {
  54435. return _super.prototype._serialize.call(this, {
  54436. name: "SetParentAction",
  54437. properties: [
  54438. BABYLON.Action._GetTargetProperty(this._target),
  54439. BABYLON.Action._GetTargetProperty(this._parent),
  54440. ]
  54441. }, parent);
  54442. };
  54443. return SetParentAction;
  54444. }(BABYLON.Action));
  54445. BABYLON.SetParentAction = SetParentAction;
  54446. var PlaySoundAction = /** @class */ (function (_super) {
  54447. __extends(PlaySoundAction, _super);
  54448. function PlaySoundAction(triggerOptions, sound, condition) {
  54449. var _this = _super.call(this, triggerOptions, condition) || this;
  54450. _this._sound = sound;
  54451. return _this;
  54452. }
  54453. PlaySoundAction.prototype._prepare = function () {
  54454. };
  54455. PlaySoundAction.prototype.execute = function () {
  54456. if (this._sound !== undefined)
  54457. this._sound.play();
  54458. };
  54459. PlaySoundAction.prototype.serialize = function (parent) {
  54460. return _super.prototype._serialize.call(this, {
  54461. name: "PlaySoundAction",
  54462. properties: [{ name: "sound", value: this._sound.name }]
  54463. }, parent);
  54464. };
  54465. return PlaySoundAction;
  54466. }(BABYLON.Action));
  54467. BABYLON.PlaySoundAction = PlaySoundAction;
  54468. var StopSoundAction = /** @class */ (function (_super) {
  54469. __extends(StopSoundAction, _super);
  54470. function StopSoundAction(triggerOptions, sound, condition) {
  54471. var _this = _super.call(this, triggerOptions, condition) || this;
  54472. _this._sound = sound;
  54473. return _this;
  54474. }
  54475. StopSoundAction.prototype._prepare = function () {
  54476. };
  54477. StopSoundAction.prototype.execute = function () {
  54478. if (this._sound !== undefined)
  54479. this._sound.stop();
  54480. };
  54481. StopSoundAction.prototype.serialize = function (parent) {
  54482. return _super.prototype._serialize.call(this, {
  54483. name: "StopSoundAction",
  54484. properties: [{ name: "sound", value: this._sound.name }]
  54485. }, parent);
  54486. };
  54487. return StopSoundAction;
  54488. }(BABYLON.Action));
  54489. BABYLON.StopSoundAction = StopSoundAction;
  54490. })(BABYLON || (BABYLON = {}));
  54491. //# sourceMappingURL=babylon.directActions.js.map
  54492. var BABYLON;
  54493. (function (BABYLON) {
  54494. var SpriteManager = /** @class */ (function () {
  54495. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54496. if (epsilon === void 0) { epsilon = 0.01; }
  54497. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54498. this.name = name;
  54499. this.sprites = new Array();
  54500. this.renderingGroupId = 0;
  54501. this.layerMask = 0x0FFFFFFF;
  54502. this.fogEnabled = true;
  54503. this.isPickable = false;
  54504. /**
  54505. * An event triggered when the manager is disposed.
  54506. */
  54507. this.onDisposeObservable = new BABYLON.Observable();
  54508. this._vertexBuffers = {};
  54509. this._capacity = capacity;
  54510. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54511. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54512. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54513. if (cellSize.width && cellSize.height) {
  54514. this.cellWidth = cellSize.width;
  54515. this.cellHeight = cellSize.height;
  54516. }
  54517. else if (cellSize !== undefined) {
  54518. this.cellWidth = cellSize;
  54519. this.cellHeight = cellSize;
  54520. }
  54521. else {
  54522. return;
  54523. }
  54524. this._epsilon = epsilon;
  54525. this._scene = scene;
  54526. this._scene.spriteManagers.push(this);
  54527. var indices = [];
  54528. var index = 0;
  54529. for (var count = 0; count < capacity; count++) {
  54530. indices.push(index);
  54531. indices.push(index + 1);
  54532. indices.push(index + 2);
  54533. indices.push(index);
  54534. indices.push(index + 2);
  54535. indices.push(index + 3);
  54536. index += 4;
  54537. }
  54538. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54539. // VBO
  54540. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54541. this._vertexData = new Float32Array(capacity * 16 * 4);
  54542. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54543. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54544. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54545. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54546. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54547. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54548. this._vertexBuffers["options"] = options;
  54549. this._vertexBuffers["cellInfo"] = cellInfo;
  54550. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54551. // Effects
  54552. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54553. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54554. }
  54555. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54556. set: function (callback) {
  54557. if (this._onDisposeObserver) {
  54558. this.onDisposeObservable.remove(this._onDisposeObserver);
  54559. }
  54560. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54561. },
  54562. enumerable: true,
  54563. configurable: true
  54564. });
  54565. Object.defineProperty(SpriteManager.prototype, "texture", {
  54566. get: function () {
  54567. return this._spriteTexture;
  54568. },
  54569. set: function (value) {
  54570. this._spriteTexture = value;
  54571. },
  54572. enumerable: true,
  54573. configurable: true
  54574. });
  54575. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54576. var arrayOffset = index * 16;
  54577. if (offsetX === 0)
  54578. offsetX = this._epsilon;
  54579. else if (offsetX === 1)
  54580. offsetX = 1 - this._epsilon;
  54581. if (offsetY === 0)
  54582. offsetY = this._epsilon;
  54583. else if (offsetY === 1)
  54584. offsetY = 1 - this._epsilon;
  54585. this._vertexData[arrayOffset] = sprite.position.x;
  54586. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54587. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54588. this._vertexData[arrayOffset + 3] = sprite.angle;
  54589. this._vertexData[arrayOffset + 4] = sprite.width;
  54590. this._vertexData[arrayOffset + 5] = sprite.height;
  54591. this._vertexData[arrayOffset + 6] = offsetX;
  54592. this._vertexData[arrayOffset + 7] = offsetY;
  54593. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54594. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54595. var offset = (sprite.cellIndex / rowSize) >> 0;
  54596. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54597. this._vertexData[arrayOffset + 11] = offset;
  54598. // Color
  54599. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54600. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54601. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54602. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54603. };
  54604. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54605. var count = Math.min(this._capacity, this.sprites.length);
  54606. var min = BABYLON.Vector3.Zero();
  54607. var max = BABYLON.Vector3.Zero();
  54608. var distance = Number.MAX_VALUE;
  54609. var currentSprite = null;
  54610. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54611. var cameraView = camera.getViewMatrix();
  54612. for (var index = 0; index < count; index++) {
  54613. var sprite = this.sprites[index];
  54614. if (!sprite) {
  54615. continue;
  54616. }
  54617. if (predicate) {
  54618. if (!predicate(sprite)) {
  54619. continue;
  54620. }
  54621. }
  54622. else if (!sprite.isPickable) {
  54623. continue;
  54624. }
  54625. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54626. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54627. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54628. if (ray.intersectsBoxMinMax(min, max)) {
  54629. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54630. if (distance > currentDistance) {
  54631. distance = currentDistance;
  54632. currentSprite = sprite;
  54633. if (fastCheck) {
  54634. break;
  54635. }
  54636. }
  54637. }
  54638. }
  54639. if (currentSprite) {
  54640. var result = new BABYLON.PickingInfo();
  54641. result.hit = true;
  54642. result.pickedSprite = currentSprite;
  54643. result.distance = distance;
  54644. return result;
  54645. }
  54646. return null;
  54647. };
  54648. SpriteManager.prototype.render = function () {
  54649. // Check
  54650. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54651. return;
  54652. var engine = this._scene.getEngine();
  54653. var baseSize = this._spriteTexture.getBaseSize();
  54654. // Sprites
  54655. var deltaTime = engine.getDeltaTime();
  54656. var max = Math.min(this._capacity, this.sprites.length);
  54657. var rowSize = baseSize.width / this.cellWidth;
  54658. var offset = 0;
  54659. for (var index = 0; index < max; index++) {
  54660. var sprite = this.sprites[index];
  54661. if (!sprite) {
  54662. continue;
  54663. }
  54664. sprite._animate(deltaTime);
  54665. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54666. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54667. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54668. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54669. }
  54670. this._buffer.update(this._vertexData);
  54671. // Render
  54672. var effect = this._effectBase;
  54673. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54674. effect = this._effectFog;
  54675. }
  54676. engine.enableEffect(effect);
  54677. var viewMatrix = this._scene.getViewMatrix();
  54678. effect.setTexture("diffuseSampler", this._spriteTexture);
  54679. effect.setMatrix("view", viewMatrix);
  54680. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54681. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54682. // Fog
  54683. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54684. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54685. effect.setColor3("vFogColor", this._scene.fogColor);
  54686. }
  54687. // VBOs
  54688. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54689. // Draw order
  54690. engine.setDepthFunctionToLessOrEqual();
  54691. effect.setBool("alphaTest", true);
  54692. engine.setColorWrite(false);
  54693. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54694. engine.setColorWrite(true);
  54695. effect.setBool("alphaTest", false);
  54696. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54697. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54698. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54699. };
  54700. SpriteManager.prototype.dispose = function () {
  54701. if (this._buffer) {
  54702. this._buffer.dispose();
  54703. this._buffer = null;
  54704. }
  54705. if (this._indexBuffer) {
  54706. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54707. this._indexBuffer = null;
  54708. }
  54709. if (this._spriteTexture) {
  54710. this._spriteTexture.dispose();
  54711. this._spriteTexture = null;
  54712. }
  54713. // Remove from scene
  54714. var index = this._scene.spriteManagers.indexOf(this);
  54715. this._scene.spriteManagers.splice(index, 1);
  54716. // Callback
  54717. this.onDisposeObservable.notifyObservers(this);
  54718. this.onDisposeObservable.clear();
  54719. };
  54720. return SpriteManager;
  54721. }());
  54722. BABYLON.SpriteManager = SpriteManager;
  54723. })(BABYLON || (BABYLON = {}));
  54724. //# sourceMappingURL=babylon.spriteManager.js.map
  54725. var BABYLON;
  54726. (function (BABYLON) {
  54727. var Sprite = /** @class */ (function () {
  54728. function Sprite(name, manager) {
  54729. this.name = name;
  54730. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54731. this.width = 1.0;
  54732. this.height = 1.0;
  54733. this.angle = 0;
  54734. this.cellIndex = 0;
  54735. this.invertU = 0;
  54736. this.invertV = 0;
  54737. this.animations = new Array();
  54738. this.isPickable = false;
  54739. this._animationStarted = false;
  54740. this._loopAnimation = false;
  54741. this._fromIndex = 0;
  54742. this._toIndex = 0;
  54743. this._delay = 0;
  54744. this._direction = 1;
  54745. this._time = 0;
  54746. this._manager = manager;
  54747. this._manager.sprites.push(this);
  54748. this.position = BABYLON.Vector3.Zero();
  54749. }
  54750. Object.defineProperty(Sprite.prototype, "size", {
  54751. get: function () {
  54752. return this.width;
  54753. },
  54754. set: function (value) {
  54755. this.width = value;
  54756. this.height = value;
  54757. },
  54758. enumerable: true,
  54759. configurable: true
  54760. });
  54761. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54762. this._fromIndex = from;
  54763. this._toIndex = to;
  54764. this._loopAnimation = loop;
  54765. this._delay = delay;
  54766. this._animationStarted = true;
  54767. this._direction = from < to ? 1 : -1;
  54768. this.cellIndex = from;
  54769. this._time = 0;
  54770. this._onAnimationEnd = onAnimationEnd;
  54771. };
  54772. Sprite.prototype.stopAnimation = function () {
  54773. this._animationStarted = false;
  54774. };
  54775. Sprite.prototype._animate = function (deltaTime) {
  54776. if (!this._animationStarted)
  54777. return;
  54778. this._time += deltaTime;
  54779. if (this._time > this._delay) {
  54780. this._time = this._time % this._delay;
  54781. this.cellIndex += this._direction;
  54782. if (this.cellIndex > this._toIndex) {
  54783. if (this._loopAnimation) {
  54784. this.cellIndex = this._fromIndex;
  54785. }
  54786. else {
  54787. this.cellIndex = this._toIndex;
  54788. this._animationStarted = false;
  54789. if (this._onAnimationEnd) {
  54790. this._onAnimationEnd();
  54791. }
  54792. if (this.disposeWhenFinishedAnimating) {
  54793. this.dispose();
  54794. }
  54795. }
  54796. }
  54797. }
  54798. };
  54799. Sprite.prototype.dispose = function () {
  54800. for (var i = 0; i < this._manager.sprites.length; i++) {
  54801. if (this._manager.sprites[i] == this) {
  54802. this._manager.sprites.splice(i, 1);
  54803. }
  54804. }
  54805. };
  54806. return Sprite;
  54807. }());
  54808. BABYLON.Sprite = Sprite;
  54809. })(BABYLON || (BABYLON = {}));
  54810. //# sourceMappingURL=babylon.sprite.js.map
  54811. var BABYLON;
  54812. (function (BABYLON) {
  54813. var IntersectionInfo = /** @class */ (function () {
  54814. function IntersectionInfo(bu, bv, distance) {
  54815. this.bu = bu;
  54816. this.bv = bv;
  54817. this.distance = distance;
  54818. this.faceId = 0;
  54819. this.subMeshId = 0;
  54820. }
  54821. return IntersectionInfo;
  54822. }());
  54823. BABYLON.IntersectionInfo = IntersectionInfo;
  54824. var PickingInfo = /** @class */ (function () {
  54825. function PickingInfo() {
  54826. this.hit = false;
  54827. this.distance = 0;
  54828. this.pickedPoint = null;
  54829. this.pickedMesh = null;
  54830. this.bu = 0;
  54831. this.bv = 0;
  54832. this.faceId = -1;
  54833. this.subMeshId = 0;
  54834. this.pickedSprite = null;
  54835. }
  54836. // Methods
  54837. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54838. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54839. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54840. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54841. return null;
  54842. }
  54843. var indices = this.pickedMesh.getIndices();
  54844. if (!indices) {
  54845. return null;
  54846. }
  54847. var result;
  54848. if (useVerticesNormals) {
  54849. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54850. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54851. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54852. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54853. normal0 = normal0.scale(this.bu);
  54854. normal1 = normal1.scale(this.bv);
  54855. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54856. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54857. }
  54858. else {
  54859. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54860. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54861. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54862. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54863. var p1p2 = vertex1.subtract(vertex2);
  54864. var p3p2 = vertex3.subtract(vertex2);
  54865. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54866. }
  54867. if (useWorldCoordinates) {
  54868. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54869. }
  54870. return BABYLON.Vector3.Normalize(result);
  54871. };
  54872. PickingInfo.prototype.getTextureCoordinates = function () {
  54873. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54874. return null;
  54875. }
  54876. var indices = this.pickedMesh.getIndices();
  54877. if (!indices) {
  54878. return null;
  54879. }
  54880. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54881. if (!uvs) {
  54882. return null;
  54883. }
  54884. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54885. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54886. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54887. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54888. uv1 = uv1.scale(this.bu);
  54889. uv2 = uv2.scale(this.bv);
  54890. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54891. };
  54892. return PickingInfo;
  54893. }());
  54894. BABYLON.PickingInfo = PickingInfo;
  54895. })(BABYLON || (BABYLON = {}));
  54896. //# sourceMappingURL=babylon.pickingInfo.js.map
  54897. var BABYLON;
  54898. (function (BABYLON) {
  54899. var Ray = /** @class */ (function () {
  54900. function Ray(origin, direction, length) {
  54901. if (length === void 0) { length = Number.MAX_VALUE; }
  54902. this.origin = origin;
  54903. this.direction = direction;
  54904. this.length = length;
  54905. }
  54906. // Methods
  54907. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54908. var d = 0.0;
  54909. var maxValue = Number.MAX_VALUE;
  54910. var inv;
  54911. var min;
  54912. var max;
  54913. var temp;
  54914. if (Math.abs(this.direction.x) < 0.0000001) {
  54915. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54916. return false;
  54917. }
  54918. }
  54919. else {
  54920. inv = 1.0 / this.direction.x;
  54921. min = (minimum.x - this.origin.x) * inv;
  54922. max = (maximum.x - this.origin.x) * inv;
  54923. if (max === -Infinity) {
  54924. max = Infinity;
  54925. }
  54926. if (min > max) {
  54927. temp = min;
  54928. min = max;
  54929. max = temp;
  54930. }
  54931. d = Math.max(min, d);
  54932. maxValue = Math.min(max, maxValue);
  54933. if (d > maxValue) {
  54934. return false;
  54935. }
  54936. }
  54937. if (Math.abs(this.direction.y) < 0.0000001) {
  54938. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54939. return false;
  54940. }
  54941. }
  54942. else {
  54943. inv = 1.0 / this.direction.y;
  54944. min = (minimum.y - this.origin.y) * inv;
  54945. max = (maximum.y - this.origin.y) * inv;
  54946. if (max === -Infinity) {
  54947. max = Infinity;
  54948. }
  54949. if (min > max) {
  54950. temp = min;
  54951. min = max;
  54952. max = temp;
  54953. }
  54954. d = Math.max(min, d);
  54955. maxValue = Math.min(max, maxValue);
  54956. if (d > maxValue) {
  54957. return false;
  54958. }
  54959. }
  54960. if (Math.abs(this.direction.z) < 0.0000001) {
  54961. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54962. return false;
  54963. }
  54964. }
  54965. else {
  54966. inv = 1.0 / this.direction.z;
  54967. min = (minimum.z - this.origin.z) * inv;
  54968. max = (maximum.z - this.origin.z) * inv;
  54969. if (max === -Infinity) {
  54970. max = Infinity;
  54971. }
  54972. if (min > max) {
  54973. temp = min;
  54974. min = max;
  54975. max = temp;
  54976. }
  54977. d = Math.max(min, d);
  54978. maxValue = Math.min(max, maxValue);
  54979. if (d > maxValue) {
  54980. return false;
  54981. }
  54982. }
  54983. return true;
  54984. };
  54985. Ray.prototype.intersectsBox = function (box) {
  54986. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54987. };
  54988. Ray.prototype.intersectsSphere = function (sphere) {
  54989. var x = sphere.center.x - this.origin.x;
  54990. var y = sphere.center.y - this.origin.y;
  54991. var z = sphere.center.z - this.origin.z;
  54992. var pyth = (x * x) + (y * y) + (z * z);
  54993. var rr = sphere.radius * sphere.radius;
  54994. if (pyth <= rr) {
  54995. return true;
  54996. }
  54997. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54998. if (dot < 0.0) {
  54999. return false;
  55000. }
  55001. var temp = pyth - (dot * dot);
  55002. return temp <= rr;
  55003. };
  55004. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55005. if (!this._edge1) {
  55006. this._edge1 = BABYLON.Vector3.Zero();
  55007. this._edge2 = BABYLON.Vector3.Zero();
  55008. this._pvec = BABYLON.Vector3.Zero();
  55009. this._tvec = BABYLON.Vector3.Zero();
  55010. this._qvec = BABYLON.Vector3.Zero();
  55011. }
  55012. vertex1.subtractToRef(vertex0, this._edge1);
  55013. vertex2.subtractToRef(vertex0, this._edge2);
  55014. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55015. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55016. if (det === 0) {
  55017. return null;
  55018. }
  55019. var invdet = 1 / det;
  55020. this.origin.subtractToRef(vertex0, this._tvec);
  55021. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55022. if (bu < 0 || bu > 1.0) {
  55023. return null;
  55024. }
  55025. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55026. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55027. if (bv < 0 || bu + bv > 1.0) {
  55028. return null;
  55029. }
  55030. //check if the distance is longer than the predefined length.
  55031. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55032. if (distance > this.length) {
  55033. return null;
  55034. }
  55035. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55036. };
  55037. Ray.prototype.intersectsPlane = function (plane) {
  55038. var distance;
  55039. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55040. if (Math.abs(result1) < 9.99999997475243E-07) {
  55041. return null;
  55042. }
  55043. else {
  55044. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55045. distance = (-plane.d - result2) / result1;
  55046. if (distance < 0.0) {
  55047. if (distance < -9.99999997475243E-07) {
  55048. return null;
  55049. }
  55050. else {
  55051. return 0;
  55052. }
  55053. }
  55054. return distance;
  55055. }
  55056. };
  55057. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55058. var tm = BABYLON.Tmp.Matrix[0];
  55059. mesh.getWorldMatrix().invertToRef(tm);
  55060. if (this._tmpRay) {
  55061. Ray.TransformToRef(this, tm, this._tmpRay);
  55062. }
  55063. else {
  55064. this._tmpRay = Ray.Transform(this, tm);
  55065. }
  55066. return mesh.intersects(this._tmpRay, fastCheck);
  55067. };
  55068. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55069. if (results) {
  55070. results.length = 0;
  55071. }
  55072. else {
  55073. results = [];
  55074. }
  55075. for (var i = 0; i < meshes.length; i++) {
  55076. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55077. if (pickInfo.hit) {
  55078. results.push(pickInfo);
  55079. }
  55080. }
  55081. results.sort(this._comparePickingInfo);
  55082. return results;
  55083. };
  55084. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55085. if (pickingInfoA.distance < pickingInfoB.distance) {
  55086. return -1;
  55087. }
  55088. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55089. return 1;
  55090. }
  55091. else {
  55092. return 0;
  55093. }
  55094. };
  55095. /**
  55096. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55097. * @param sega the first point of the segment to test the intersection against
  55098. * @param segb the second point of the segment to test the intersection against
  55099. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55100. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55101. */
  55102. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55103. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55104. var u = segb.subtract(sega);
  55105. var v = rsegb.subtract(this.origin);
  55106. var w = sega.subtract(this.origin);
  55107. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55108. var b = BABYLON.Vector3.Dot(u, v);
  55109. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55110. var d = BABYLON.Vector3.Dot(u, w);
  55111. var e = BABYLON.Vector3.Dot(v, w);
  55112. var D = a * c - b * b; // always >= 0
  55113. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55114. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55115. // compute the line parameters of the two closest points
  55116. if (D < Ray.smallnum) { // the lines are almost parallel
  55117. sN = 0.0; // force using point P0 on segment S1
  55118. sD = 1.0; // to prevent possible division by 0.0 later
  55119. tN = e;
  55120. tD = c;
  55121. }
  55122. else { // get the closest points on the infinite lines
  55123. sN = (b * e - c * d);
  55124. tN = (a * e - b * d);
  55125. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55126. sN = 0.0;
  55127. tN = e;
  55128. tD = c;
  55129. }
  55130. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55131. sN = sD;
  55132. tN = e + b;
  55133. tD = c;
  55134. }
  55135. }
  55136. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55137. tN = 0.0;
  55138. // recompute sc for this edge
  55139. if (-d < 0.0) {
  55140. sN = 0.0;
  55141. }
  55142. else if (-d > a)
  55143. sN = sD;
  55144. else {
  55145. sN = -d;
  55146. sD = a;
  55147. }
  55148. }
  55149. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55150. tN = tD;
  55151. // recompute sc for this edge
  55152. if ((-d + b) < 0.0) {
  55153. sN = 0;
  55154. }
  55155. else if ((-d + b) > a) {
  55156. sN = sD;
  55157. }
  55158. else {
  55159. sN = (-d + b);
  55160. sD = a;
  55161. }
  55162. }
  55163. // finally do the division to get sc and tc
  55164. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55165. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55166. // get the difference of the two closest points
  55167. var qtc = v.multiplyByFloats(tc, tc, tc);
  55168. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55169. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55170. if (isIntersected) {
  55171. return qtc.length();
  55172. }
  55173. return -1;
  55174. };
  55175. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55176. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55177. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55178. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55179. this.direction.normalize();
  55180. return this;
  55181. };
  55182. // Statics
  55183. Ray.Zero = function () {
  55184. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55185. };
  55186. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55187. var result = Ray.Zero();
  55188. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55189. };
  55190. /**
  55191. * 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
  55192. * transformed to the given world matrix.
  55193. * @param origin The origin point
  55194. * @param end The end point
  55195. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55196. */
  55197. Ray.CreateNewFromTo = function (origin, end, world) {
  55198. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55199. var direction = end.subtract(origin);
  55200. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55201. direction.normalize();
  55202. return Ray.Transform(new Ray(origin, direction, length), world);
  55203. };
  55204. Ray.Transform = function (ray, matrix) {
  55205. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55206. Ray.TransformToRef(ray, matrix, result);
  55207. return result;
  55208. };
  55209. Ray.TransformToRef = function (ray, matrix, result) {
  55210. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55211. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55212. result.length = ray.length;
  55213. var dir = result.direction;
  55214. var len = dir.length();
  55215. if (!(len === 0 || len === 1)) {
  55216. var num = 1.0 / len;
  55217. dir.x *= num;
  55218. dir.y *= num;
  55219. dir.z *= num;
  55220. result.length *= len;
  55221. }
  55222. };
  55223. Ray.smallnum = 0.00000001;
  55224. Ray.rayl = 10e8;
  55225. return Ray;
  55226. }());
  55227. BABYLON.Ray = Ray;
  55228. })(BABYLON || (BABYLON = {}));
  55229. //# sourceMappingURL=babylon.ray.js.map
  55230. var BABYLON;
  55231. (function (BABYLON) {
  55232. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55233. if (boxMin.x > sphereCenter.x + sphereRadius)
  55234. return false;
  55235. if (sphereCenter.x - sphereRadius > boxMax.x)
  55236. return false;
  55237. if (boxMin.y > sphereCenter.y + sphereRadius)
  55238. return false;
  55239. if (sphereCenter.y - sphereRadius > boxMax.y)
  55240. return false;
  55241. if (boxMin.z > sphereCenter.z + sphereRadius)
  55242. return false;
  55243. if (sphereCenter.z - sphereRadius > boxMax.z)
  55244. return false;
  55245. return true;
  55246. };
  55247. var getLowestRoot = (function () {
  55248. var result = { root: 0, found: false };
  55249. return function (a, b, c, maxR) {
  55250. result.root = 0;
  55251. result.found = false;
  55252. var determinant = b * b - 4.0 * a * c;
  55253. if (determinant < 0)
  55254. return result;
  55255. var sqrtD = Math.sqrt(determinant);
  55256. var r1 = (-b - sqrtD) / (2.0 * a);
  55257. var r2 = (-b + sqrtD) / (2.0 * a);
  55258. if (r1 > r2) {
  55259. var temp = r2;
  55260. r2 = r1;
  55261. r1 = temp;
  55262. }
  55263. if (r1 > 0 && r1 < maxR) {
  55264. result.root = r1;
  55265. result.found = true;
  55266. return result;
  55267. }
  55268. if (r2 > 0 && r2 < maxR) {
  55269. result.root = r2;
  55270. result.found = true;
  55271. return result;
  55272. }
  55273. return result;
  55274. };
  55275. })();
  55276. var Collider = /** @class */ (function () {
  55277. function Collider() {
  55278. this._collisionPoint = BABYLON.Vector3.Zero();
  55279. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55280. this._tempVector = BABYLON.Vector3.Zero();
  55281. this._tempVector2 = BABYLON.Vector3.Zero();
  55282. this._tempVector3 = BABYLON.Vector3.Zero();
  55283. this._tempVector4 = BABYLON.Vector3.Zero();
  55284. this._edge = BABYLON.Vector3.Zero();
  55285. this._baseToVertex = BABYLON.Vector3.Zero();
  55286. this._destinationPoint = BABYLON.Vector3.Zero();
  55287. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55288. this._displacementVector = BABYLON.Vector3.Zero();
  55289. this._radius = BABYLON.Vector3.One();
  55290. this._retry = 0;
  55291. this._basePointWorld = BABYLON.Vector3.Zero();
  55292. this._velocityWorld = BABYLON.Vector3.Zero();
  55293. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55294. this._collisionMask = -1;
  55295. }
  55296. Object.defineProperty(Collider.prototype, "collisionMask", {
  55297. get: function () {
  55298. return this._collisionMask;
  55299. },
  55300. set: function (mask) {
  55301. this._collisionMask = !isNaN(mask) ? mask : -1;
  55302. },
  55303. enumerable: true,
  55304. configurable: true
  55305. });
  55306. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55307. /**
  55308. * Gets the plane normal used to compute the sliding response (in local space)
  55309. */
  55310. get: function () {
  55311. return this._slidePlaneNormal;
  55312. },
  55313. enumerable: true,
  55314. configurable: true
  55315. });
  55316. // Methods
  55317. Collider.prototype._initialize = function (source, dir, e) {
  55318. this._velocity = dir;
  55319. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55320. this._basePoint = source;
  55321. source.multiplyToRef(this._radius, this._basePointWorld);
  55322. dir.multiplyToRef(this._radius, this._velocityWorld);
  55323. this._velocityWorldLength = this._velocityWorld.length();
  55324. this._epsilon = e;
  55325. this.collisionFound = false;
  55326. };
  55327. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55328. pa.subtractToRef(point, this._tempVector);
  55329. pb.subtractToRef(point, this._tempVector2);
  55330. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55331. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55332. if (d < 0)
  55333. return false;
  55334. pc.subtractToRef(point, this._tempVector3);
  55335. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55336. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55337. if (d < 0)
  55338. return false;
  55339. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55340. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55341. return d >= 0;
  55342. };
  55343. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55344. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55345. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55346. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55347. return false;
  55348. }
  55349. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55350. return false;
  55351. return true;
  55352. };
  55353. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55354. var t0;
  55355. var embeddedInPlane = false;
  55356. //defensive programming, actually not needed.
  55357. if (!trianglePlaneArray) {
  55358. trianglePlaneArray = [];
  55359. }
  55360. if (!trianglePlaneArray[faceIndex]) {
  55361. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55362. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55363. }
  55364. var trianglePlane = trianglePlaneArray[faceIndex];
  55365. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55366. return;
  55367. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55368. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55369. if (normalDotVelocity == 0) {
  55370. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55371. return;
  55372. embeddedInPlane = true;
  55373. t0 = 0;
  55374. }
  55375. else {
  55376. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55377. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55378. if (t0 > t1) {
  55379. var temp = t1;
  55380. t1 = t0;
  55381. t0 = temp;
  55382. }
  55383. if (t0 > 1.0 || t1 < 0.0)
  55384. return;
  55385. if (t0 < 0)
  55386. t0 = 0;
  55387. if (t0 > 1.0)
  55388. t0 = 1.0;
  55389. }
  55390. this._collisionPoint.copyFromFloats(0, 0, 0);
  55391. var found = false;
  55392. var t = 1.0;
  55393. if (!embeddedInPlane) {
  55394. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55395. this._velocity.scaleToRef(t0, this._tempVector);
  55396. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55397. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55398. found = true;
  55399. t = t0;
  55400. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55401. }
  55402. }
  55403. if (!found) {
  55404. var velocitySquaredLength = this._velocity.lengthSquared();
  55405. var a = velocitySquaredLength;
  55406. this._basePoint.subtractToRef(p1, this._tempVector);
  55407. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55408. var c = this._tempVector.lengthSquared() - 1.0;
  55409. var lowestRoot = getLowestRoot(a, b, c, t);
  55410. if (lowestRoot.found) {
  55411. t = lowestRoot.root;
  55412. found = true;
  55413. this._collisionPoint.copyFrom(p1);
  55414. }
  55415. this._basePoint.subtractToRef(p2, this._tempVector);
  55416. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55417. c = this._tempVector.lengthSquared() - 1.0;
  55418. lowestRoot = getLowestRoot(a, b, c, t);
  55419. if (lowestRoot.found) {
  55420. t = lowestRoot.root;
  55421. found = true;
  55422. this._collisionPoint.copyFrom(p2);
  55423. }
  55424. this._basePoint.subtractToRef(p3, this._tempVector);
  55425. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55426. c = this._tempVector.lengthSquared() - 1.0;
  55427. lowestRoot = getLowestRoot(a, b, c, t);
  55428. if (lowestRoot.found) {
  55429. t = lowestRoot.root;
  55430. found = true;
  55431. this._collisionPoint.copyFrom(p3);
  55432. }
  55433. p2.subtractToRef(p1, this._edge);
  55434. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55435. var edgeSquaredLength = this._edge.lengthSquared();
  55436. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55437. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55438. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55439. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55440. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55441. lowestRoot = getLowestRoot(a, b, c, t);
  55442. if (lowestRoot.found) {
  55443. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55444. if (f >= 0.0 && f <= 1.0) {
  55445. t = lowestRoot.root;
  55446. found = true;
  55447. this._edge.scaleInPlace(f);
  55448. p1.addToRef(this._edge, this._collisionPoint);
  55449. }
  55450. }
  55451. p3.subtractToRef(p2, this._edge);
  55452. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55453. edgeSquaredLength = this._edge.lengthSquared();
  55454. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55455. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55456. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55457. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55458. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55459. lowestRoot = getLowestRoot(a, b, c, t);
  55460. if (lowestRoot.found) {
  55461. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55462. if (f >= 0.0 && f <= 1.0) {
  55463. t = lowestRoot.root;
  55464. found = true;
  55465. this._edge.scaleInPlace(f);
  55466. p2.addToRef(this._edge, this._collisionPoint);
  55467. }
  55468. }
  55469. p1.subtractToRef(p3, this._edge);
  55470. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55471. edgeSquaredLength = this._edge.lengthSquared();
  55472. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55473. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55474. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55475. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55476. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55477. lowestRoot = getLowestRoot(a, b, c, t);
  55478. if (lowestRoot.found) {
  55479. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55480. if (f >= 0.0 && f <= 1.0) {
  55481. t = lowestRoot.root;
  55482. found = true;
  55483. this._edge.scaleInPlace(f);
  55484. p3.addToRef(this._edge, this._collisionPoint);
  55485. }
  55486. }
  55487. }
  55488. if (found) {
  55489. var distToCollision = t * this._velocity.length();
  55490. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55491. if (!this.intersectionPoint) {
  55492. this.intersectionPoint = this._collisionPoint.clone();
  55493. }
  55494. else {
  55495. this.intersectionPoint.copyFrom(this._collisionPoint);
  55496. }
  55497. this._nearestDistance = distToCollision;
  55498. this.collisionFound = true;
  55499. }
  55500. }
  55501. };
  55502. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55503. for (var i = indexStart; i < indexEnd; i += 3) {
  55504. var p1 = pts[indices[i] - decal];
  55505. var p2 = pts[indices[i + 1] - decal];
  55506. var p3 = pts[indices[i + 2] - decal];
  55507. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55508. }
  55509. };
  55510. Collider.prototype._getResponse = function (pos, vel) {
  55511. pos.addToRef(vel, this._destinationPoint);
  55512. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55513. this._basePoint.addToRef(vel, pos);
  55514. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55515. this._slidePlaneNormal.normalize();
  55516. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55517. pos.addInPlace(this._displacementVector);
  55518. this.intersectionPoint.addInPlace(this._displacementVector);
  55519. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55520. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55521. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55522. };
  55523. return Collider;
  55524. }());
  55525. BABYLON.Collider = Collider;
  55526. })(BABYLON || (BABYLON = {}));
  55527. //# sourceMappingURL=babylon.collider.js.map
  55528. var BABYLON;
  55529. (function (BABYLON) {
  55530. //WebWorker code will be inserted to this variable.
  55531. BABYLON.CollisionWorker = "";
  55532. /** Defines supported task for worker process */
  55533. var WorkerTaskType;
  55534. (function (WorkerTaskType) {
  55535. /** Initialization */
  55536. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55537. /** Update of geometry */
  55538. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55539. /** Evaluate collision */
  55540. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55541. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55542. /** Defines kind of replies returned by worker */
  55543. var WorkerReplyType;
  55544. (function (WorkerReplyType) {
  55545. /** Success */
  55546. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55547. /** Unkown error */
  55548. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55549. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55550. var CollisionCoordinatorWorker = /** @class */ (function () {
  55551. function CollisionCoordinatorWorker() {
  55552. var _this = this;
  55553. this._scaledPosition = BABYLON.Vector3.Zero();
  55554. this._scaledVelocity = BABYLON.Vector3.Zero();
  55555. this.onMeshUpdated = function (transformNode) {
  55556. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55557. };
  55558. this.onGeometryUpdated = function (geometry) {
  55559. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55560. };
  55561. this._afterRender = function () {
  55562. if (!_this._init)
  55563. return;
  55564. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55565. return;
  55566. }
  55567. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55568. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55569. if (_this._runningUpdated > 4) {
  55570. return;
  55571. }
  55572. ++_this._runningUpdated;
  55573. var payload = {
  55574. updatedMeshes: _this._addUpdateMeshesList,
  55575. updatedGeometries: _this._addUpdateGeometriesList,
  55576. removedGeometries: _this._toRemoveGeometryArray,
  55577. removedMeshes: _this._toRemoveMeshesArray
  55578. };
  55579. var message = {
  55580. payload: payload,
  55581. taskType: WorkerTaskType.UPDATE
  55582. };
  55583. var serializable = [];
  55584. for (var id in payload.updatedGeometries) {
  55585. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55586. //prepare transferables
  55587. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55588. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55589. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55590. }
  55591. }
  55592. _this._worker.postMessage(message, serializable);
  55593. _this._addUpdateMeshesList = {};
  55594. _this._addUpdateGeometriesList = {};
  55595. _this._toRemoveGeometryArray = [];
  55596. _this._toRemoveMeshesArray = [];
  55597. };
  55598. this._onMessageFromWorker = function (e) {
  55599. var returnData = e.data;
  55600. if (returnData.error != WorkerReplyType.SUCCESS) {
  55601. //TODO what errors can be returned from the worker?
  55602. BABYLON.Tools.Warn("error returned from worker!");
  55603. return;
  55604. }
  55605. switch (returnData.taskType) {
  55606. case WorkerTaskType.INIT:
  55607. _this._init = true;
  55608. //Update the worked with ALL of the scene's current state
  55609. _this._scene.meshes.forEach(function (mesh) {
  55610. _this.onMeshAdded(mesh);
  55611. });
  55612. _this._scene.getGeometries().forEach(function (geometry) {
  55613. _this.onGeometryAdded(geometry);
  55614. });
  55615. break;
  55616. case WorkerTaskType.UPDATE:
  55617. _this._runningUpdated--;
  55618. break;
  55619. case WorkerTaskType.COLLIDE:
  55620. var returnPayload = returnData.payload;
  55621. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55622. return;
  55623. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55624. if (callback) {
  55625. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55626. if (mesh) {
  55627. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55628. }
  55629. }
  55630. //cleanup
  55631. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55632. break;
  55633. }
  55634. };
  55635. this._collisionsCallbackArray = [];
  55636. this._init = false;
  55637. this._runningUpdated = 0;
  55638. this._addUpdateMeshesList = {};
  55639. this._addUpdateGeometriesList = {};
  55640. this._toRemoveGeometryArray = [];
  55641. this._toRemoveMeshesArray = [];
  55642. }
  55643. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55644. if (!this._init)
  55645. return;
  55646. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55647. return;
  55648. position.divideToRef(collider._radius, this._scaledPosition);
  55649. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55650. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55651. var payload = {
  55652. collider: {
  55653. position: this._scaledPosition.asArray(),
  55654. velocity: this._scaledVelocity.asArray(),
  55655. radius: collider._radius.asArray()
  55656. },
  55657. collisionId: collisionIndex,
  55658. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55659. maximumRetry: maximumRetry
  55660. };
  55661. var message = {
  55662. payload: payload,
  55663. taskType: WorkerTaskType.COLLIDE
  55664. };
  55665. this._worker.postMessage(message);
  55666. };
  55667. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55668. this._scene = scene;
  55669. this._scene.registerAfterRender(this._afterRender);
  55670. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55671. this._worker = new Worker(workerUrl);
  55672. this._worker.onmessage = this._onMessageFromWorker;
  55673. var message = {
  55674. payload: {},
  55675. taskType: WorkerTaskType.INIT
  55676. };
  55677. this._worker.postMessage(message);
  55678. };
  55679. CollisionCoordinatorWorker.prototype.destroy = function () {
  55680. this._scene.unregisterAfterRender(this._afterRender);
  55681. this._worker.terminate();
  55682. };
  55683. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55684. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55685. this.onMeshUpdated(mesh);
  55686. };
  55687. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55688. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55689. };
  55690. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55691. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55692. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55693. this.onGeometryUpdated(geometry);
  55694. };
  55695. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55696. this._toRemoveGeometryArray.push(geometry.id);
  55697. };
  55698. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55699. var submeshes = [];
  55700. if (mesh.subMeshes) {
  55701. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55702. var boundingInfo = sm.getBoundingInfo();
  55703. return {
  55704. position: idx,
  55705. verticesStart: sm.verticesStart,
  55706. verticesCount: sm.verticesCount,
  55707. indexStart: sm.indexStart,
  55708. indexCount: sm.indexCount,
  55709. hasMaterial: !!sm.getMaterial(),
  55710. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55711. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55712. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55713. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55714. };
  55715. });
  55716. }
  55717. var geometryId = null;
  55718. if (mesh instanceof BABYLON.Mesh) {
  55719. var geometry = mesh.geometry;
  55720. geometryId = geometry ? geometry.id : null;
  55721. }
  55722. else if (mesh instanceof BABYLON.InstancedMesh) {
  55723. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55724. geometryId = geometry ? geometry.id : null;
  55725. }
  55726. var boundingInfo = mesh.getBoundingInfo();
  55727. return {
  55728. uniqueId: mesh.uniqueId,
  55729. id: mesh.id,
  55730. name: mesh.name,
  55731. geometryId: geometryId,
  55732. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55733. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55734. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55735. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55736. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55737. subMeshes: submeshes,
  55738. checkCollisions: mesh.checkCollisions
  55739. };
  55740. };
  55741. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55742. return {
  55743. id: geometry.id,
  55744. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55745. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55746. indices: new Uint32Array(geometry.getIndices() || []),
  55747. };
  55748. };
  55749. return CollisionCoordinatorWorker;
  55750. }());
  55751. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55752. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55753. function CollisionCoordinatorLegacy() {
  55754. this._scaledPosition = BABYLON.Vector3.Zero();
  55755. this._scaledVelocity = BABYLON.Vector3.Zero();
  55756. this._finalPosition = BABYLON.Vector3.Zero();
  55757. }
  55758. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55759. position.divideToRef(collider._radius, this._scaledPosition);
  55760. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55761. collider.collidedMesh = null;
  55762. collider._retry = 0;
  55763. collider._initialVelocity = this._scaledVelocity;
  55764. collider._initialPosition = this._scaledPosition;
  55765. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55766. this._finalPosition.multiplyInPlace(collider._radius);
  55767. //run the callback
  55768. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55769. };
  55770. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55771. this._scene = scene;
  55772. };
  55773. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55774. //Legacy need no destruction method.
  55775. };
  55776. //No update in legacy mode
  55777. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55778. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55779. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55780. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55781. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55782. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55783. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55784. if (excludedMesh === void 0) { excludedMesh = null; }
  55785. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55786. if (collider._retry >= maximumRetry) {
  55787. finalPosition.copyFrom(position);
  55788. return;
  55789. }
  55790. // Check if this is a mesh else camera or -1
  55791. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55792. collider._initialize(position, velocity, closeDistance);
  55793. // Check all meshes
  55794. for (var index = 0; index < this._scene.meshes.length; index++) {
  55795. var mesh = this._scene.meshes[index];
  55796. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55797. mesh._checkCollision(collider);
  55798. }
  55799. }
  55800. if (!collider.collisionFound) {
  55801. position.addToRef(velocity, finalPosition);
  55802. return;
  55803. }
  55804. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55805. collider._getResponse(position, velocity);
  55806. }
  55807. if (velocity.length() <= closeDistance) {
  55808. finalPosition.copyFrom(position);
  55809. return;
  55810. }
  55811. collider._retry++;
  55812. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55813. };
  55814. return CollisionCoordinatorLegacy;
  55815. }());
  55816. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55817. })(BABYLON || (BABYLON = {}));
  55818. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55819. var BABYLON;
  55820. (function (BABYLON) {
  55821. /**
  55822. * A particle represents one of the element emitted by a particle system.
  55823. * This is mainly define by its coordinates, direction, velocity and age.
  55824. */
  55825. var Particle = /** @class */ (function () {
  55826. /**
  55827. * Creates a new instance Particle
  55828. * @param particleSystem the particle system the particle belongs to
  55829. */
  55830. function Particle(
  55831. /**
  55832. * particleSystem the particle system the particle belongs to.
  55833. */
  55834. particleSystem) {
  55835. this.particleSystem = particleSystem;
  55836. /**
  55837. * The world position of the particle in the scene.
  55838. */
  55839. this.position = BABYLON.Vector3.Zero();
  55840. /**
  55841. * The world direction of the particle in the scene.
  55842. */
  55843. this.direction = BABYLON.Vector3.Zero();
  55844. /**
  55845. * The color of the particle.
  55846. */
  55847. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55848. /**
  55849. * The color change of the particle per step.
  55850. */
  55851. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55852. /**
  55853. * Defines how long will the life of the particle be.
  55854. */
  55855. this.lifeTime = 1.0;
  55856. /**
  55857. * The current age of the particle.
  55858. */
  55859. this.age = 0;
  55860. /**
  55861. * The current size of the particle.
  55862. */
  55863. this.size = 0;
  55864. /**
  55865. * The current angle of the particle.
  55866. */
  55867. this.angle = 0;
  55868. /**
  55869. * Defines how fast is the angle changing.
  55870. */
  55871. this.angularSpeed = 0;
  55872. /**
  55873. * Defines the cell index used by the particle to be rendered from a sprite.
  55874. */
  55875. this.cellIndex = 0;
  55876. this._currentFrameCounter = 0;
  55877. if (!this.particleSystem.isAnimationSheetEnabled) {
  55878. return;
  55879. }
  55880. this.updateCellInfoFromSystem();
  55881. }
  55882. Particle.prototype.updateCellInfoFromSystem = function () {
  55883. this.cellIndex = this.particleSystem.startSpriteCellID;
  55884. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55885. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55886. }
  55887. else {
  55888. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55889. }
  55890. };
  55891. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55892. // (ageOffset / scaledUpdateSpeed) / available cells
  55893. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55894. this._currentFrameCounter += scaledUpdateSpeed;
  55895. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55896. this._currentFrameCounter = 0;
  55897. this.cellIndex++;
  55898. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55899. this.cellIndex = this.particleSystem.endSpriteCellID;
  55900. }
  55901. }
  55902. };
  55903. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55904. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55905. this.cellIndex++;
  55906. this._currentFrameCounter = 0;
  55907. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55908. if (this.particleSystem.spriteCellLoop) {
  55909. this.cellIndex = this.particleSystem.startSpriteCellID;
  55910. }
  55911. else {
  55912. this.cellIndex = this.particleSystem.endSpriteCellID;
  55913. }
  55914. }
  55915. }
  55916. else {
  55917. this._currentFrameCounter++;
  55918. }
  55919. };
  55920. /**
  55921. * Copy the properties of particle to another one.
  55922. * @param other the particle to copy the information to.
  55923. */
  55924. Particle.prototype.copyTo = function (other) {
  55925. other.position.copyFrom(this.position);
  55926. other.direction.copyFrom(this.direction);
  55927. other.color.copyFrom(this.color);
  55928. other.colorStep.copyFrom(this.colorStep);
  55929. other.lifeTime = this.lifeTime;
  55930. other.age = this.age;
  55931. other.size = this.size;
  55932. other.angle = this.angle;
  55933. other.angularSpeed = this.angularSpeed;
  55934. other.particleSystem = this.particleSystem;
  55935. other.cellIndex = this.cellIndex;
  55936. };
  55937. return Particle;
  55938. }());
  55939. BABYLON.Particle = Particle;
  55940. })(BABYLON || (BABYLON = {}));
  55941. //# sourceMappingURL=babylon.particle.js.map
  55942. var BABYLON;
  55943. (function (BABYLON) {
  55944. /**
  55945. * This represents a particle system in Babylon.
  55946. * 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.
  55947. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55948. * @example https://doc.babylonjs.com/babylon101/particles
  55949. */
  55950. var ParticleSystem = /** @class */ (function () {
  55951. /**
  55952. * Instantiates a particle system.
  55953. * 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.
  55954. * @param name The name of the particle system
  55955. * @param capacity The max number of particles alive at the same time
  55956. * @param scene The scene the particle system belongs to
  55957. * @param customEffect a custom effect used to change the way particles are rendered by default
  55958. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55959. * @param epsilon Offset used to render the particles
  55960. */
  55961. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55962. if (customEffect === void 0) { customEffect = null; }
  55963. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55964. if (epsilon === void 0) { epsilon = 0.01; }
  55965. var _this = this;
  55966. /**
  55967. * List of animations used by the particle system.
  55968. */
  55969. this.animations = [];
  55970. /**
  55971. * The rendering group used by the Particle system to chose when to render.
  55972. */
  55973. this.renderingGroupId = 0;
  55974. /**
  55975. * The emitter represents the Mesh or position we are attaching the particle system to.
  55976. */
  55977. this.emitter = null;
  55978. /**
  55979. * The maximum number of particles to emit per frame
  55980. */
  55981. this.emitRate = 10;
  55982. /**
  55983. * If you want to launch only a few particles at once, that can be done, as well.
  55984. */
  55985. this.manualEmitCount = -1;
  55986. /**
  55987. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55988. */
  55989. this.updateSpeed = 0.01;
  55990. /**
  55991. * The amount of time the particle system is running (depends of the overall update speed).
  55992. */
  55993. this.targetStopDuration = 0;
  55994. /**
  55995. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55996. */
  55997. this.disposeOnStop = false;
  55998. /**
  55999. * Minimum power of emitting particles.
  56000. */
  56001. this.minEmitPower = 1;
  56002. /**
  56003. * Maximum power of emitting particles.
  56004. */
  56005. this.maxEmitPower = 1;
  56006. /**
  56007. * Minimum life time of emitting particles.
  56008. */
  56009. this.minLifeTime = 1;
  56010. /**
  56011. * Maximum life time of emitting particles.
  56012. */
  56013. this.maxLifeTime = 1;
  56014. /**
  56015. * Minimum Size of emitting particles.
  56016. */
  56017. this.minSize = 1;
  56018. /**
  56019. * Maximum Size of emitting particles.
  56020. */
  56021. this.maxSize = 1;
  56022. /**
  56023. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56024. */
  56025. this.minAngularSpeed = 0;
  56026. /**
  56027. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56028. */
  56029. this.maxAngularSpeed = 0;
  56030. /**
  56031. * The layer mask we are rendering the particles through.
  56032. */
  56033. this.layerMask = 0x0FFFFFFF;
  56034. /**
  56035. * This can help using your own shader to render the particle system.
  56036. * The according effect will be created
  56037. */
  56038. this.customShader = null;
  56039. /**
  56040. * By default particle system starts as soon as they are created. This prevents the
  56041. * automatic start to happen and let you decide when to start emitting particles.
  56042. */
  56043. this.preventAutoStart = false;
  56044. /**
  56045. * Callback triggered when the particle animation is ending.
  56046. */
  56047. this.onAnimationEnd = null;
  56048. /**
  56049. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56050. */
  56051. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  56052. /**
  56053. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56054. * to override the particles.
  56055. */
  56056. this.forceDepthWrite = false;
  56057. /**
  56058. * You can use gravity if you want to give an orientation to your particles.
  56059. */
  56060. this.gravity = BABYLON.Vector3.Zero();
  56061. /**
  56062. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56063. */
  56064. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56065. /**
  56066. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56067. */
  56068. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56069. /**
  56070. * Color the particle will have at the end of its lifetime.
  56071. */
  56072. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56073. /**
  56074. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  56075. */
  56076. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56077. /**
  56078. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  56079. */
  56080. this.spriteCellLoop = true;
  56081. /**
  56082. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  56083. */
  56084. this.spriteCellChangeSpeed = 0;
  56085. /**
  56086. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  56087. */
  56088. this.startSpriteCellID = 0;
  56089. /**
  56090. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  56091. */
  56092. this.endSpriteCellID = 0;
  56093. /**
  56094. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  56095. */
  56096. this.spriteCellWidth = 0;
  56097. /**
  56098. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  56099. */
  56100. this.spriteCellHeight = 0;
  56101. /**
  56102. * An event triggered when the system is disposed.
  56103. */
  56104. this.onDisposeObservable = new BABYLON.Observable();
  56105. this._particles = new Array();
  56106. this._stockParticles = new Array();
  56107. this._newPartsExcess = 0;
  56108. this._vertexBuffers = {};
  56109. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56110. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56111. this._scaledDirection = BABYLON.Vector3.Zero();
  56112. this._scaledGravity = BABYLON.Vector3.Zero();
  56113. this._currentRenderId = -1;
  56114. this._started = false;
  56115. this._stopped = false;
  56116. this._actualFrame = 0;
  56117. this._vertexBufferSize = 11;
  56118. // start of sub system methods
  56119. /**
  56120. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56121. * Its lifetime will start back at 0.
  56122. */
  56123. this.recycleParticle = function (particle) {
  56124. var lastParticle = _this._particles.pop();
  56125. if (lastParticle !== particle) {
  56126. lastParticle.copyTo(particle);
  56127. }
  56128. _this._stockParticles.push(lastParticle);
  56129. };
  56130. this._createParticle = function () {
  56131. var particle;
  56132. if (_this._stockParticles.length !== 0) {
  56133. particle = _this._stockParticles.pop();
  56134. particle.age = 0;
  56135. particle.cellIndex = _this.startSpriteCellID;
  56136. }
  56137. else {
  56138. particle = new BABYLON.Particle(_this);
  56139. }
  56140. return particle;
  56141. };
  56142. this._emitFromParticle = function (particle) {
  56143. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56144. return;
  56145. }
  56146. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56147. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56148. subSystem._rootParticleSystem = _this;
  56149. _this.activeSubSystems.push(subSystem);
  56150. subSystem.start();
  56151. };
  56152. this._appendParticleVertexes = null;
  56153. this.id = name;
  56154. this.name = name;
  56155. this._capacity = capacity;
  56156. this._epsilon = epsilon;
  56157. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56158. if (isAnimationSheetEnabled) {
  56159. this._vertexBufferSize = 12;
  56160. }
  56161. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56162. this._customEffect = customEffect;
  56163. scene.particleSystems.push(this);
  56164. this._createIndexBuffer();
  56165. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  56166. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56167. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56168. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56169. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56170. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  56171. if (this._isAnimationSheetEnabled) {
  56172. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  56173. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56174. }
  56175. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56176. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56177. this._vertexBuffers["options"] = options;
  56178. // Default emitter type
  56179. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56180. this.updateFunction = function (particles) {
  56181. for (var index = 0; index < particles.length; index++) {
  56182. var particle = particles[index];
  56183. particle.age += _this._scaledUpdateSpeed;
  56184. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56185. _this._emitFromParticle(particle);
  56186. _this.recycleParticle(particle);
  56187. index--;
  56188. continue;
  56189. }
  56190. else {
  56191. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56192. particle.color.addInPlace(_this._scaledColorStep);
  56193. if (particle.color.a < 0)
  56194. particle.color.a = 0;
  56195. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56196. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56197. particle.position.addInPlace(_this._scaledDirection);
  56198. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56199. particle.direction.addInPlace(_this._scaledGravity);
  56200. if (_this._isAnimationSheetEnabled) {
  56201. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56202. }
  56203. }
  56204. }
  56205. };
  56206. }
  56207. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56208. /**
  56209. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56210. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56211. */
  56212. get: function () {
  56213. if (this.particleEmitterType.direction1) {
  56214. return this.particleEmitterType.direction1;
  56215. }
  56216. return BABYLON.Vector3.Zero();
  56217. },
  56218. set: function (value) {
  56219. if (this.particleEmitterType.direction1) {
  56220. this.particleEmitterType.direction1 = value;
  56221. }
  56222. },
  56223. enumerable: true,
  56224. configurable: true
  56225. });
  56226. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56227. /**
  56228. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56229. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56230. */
  56231. get: function () {
  56232. if (this.particleEmitterType.direction2) {
  56233. return this.particleEmitterType.direction2;
  56234. }
  56235. return BABYLON.Vector3.Zero();
  56236. },
  56237. set: function (value) {
  56238. if (this.particleEmitterType.direction2) {
  56239. this.particleEmitterType.direction2 = value;
  56240. }
  56241. },
  56242. enumerable: true,
  56243. configurable: true
  56244. });
  56245. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56246. /**
  56247. * 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.
  56248. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56249. */
  56250. get: function () {
  56251. if (this.particleEmitterType.minEmitBox) {
  56252. return this.particleEmitterType.minEmitBox;
  56253. }
  56254. return BABYLON.Vector3.Zero();
  56255. },
  56256. set: function (value) {
  56257. if (this.particleEmitterType.minEmitBox) {
  56258. this.particleEmitterType.minEmitBox = value;
  56259. }
  56260. },
  56261. enumerable: true,
  56262. configurable: true
  56263. });
  56264. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56265. /**
  56266. * 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.
  56267. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56268. */
  56269. get: function () {
  56270. if (this.particleEmitterType.maxEmitBox) {
  56271. return this.particleEmitterType.maxEmitBox;
  56272. }
  56273. return BABYLON.Vector3.Zero();
  56274. },
  56275. set: function (value) {
  56276. if (this.particleEmitterType.maxEmitBox) {
  56277. this.particleEmitterType.maxEmitBox = value;
  56278. }
  56279. },
  56280. enumerable: true,
  56281. configurable: true
  56282. });
  56283. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56284. /**
  56285. * Sets a callback that will be triggered when the system is disposed.
  56286. */
  56287. set: function (callback) {
  56288. if (this._onDisposeObserver) {
  56289. this.onDisposeObservable.remove(this._onDisposeObserver);
  56290. }
  56291. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56292. },
  56293. enumerable: true,
  56294. configurable: true
  56295. });
  56296. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56297. /**
  56298. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56299. */
  56300. get: function () {
  56301. return this._isAnimationSheetEnabled;
  56302. },
  56303. enumerable: true,
  56304. configurable: true
  56305. });
  56306. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56307. //end of Sub-emitter
  56308. /**
  56309. * Gets the current list of active particles
  56310. */
  56311. get: function () {
  56312. return this._particles;
  56313. },
  56314. enumerable: true,
  56315. configurable: true
  56316. });
  56317. /**
  56318. * Returns the string "ParticleSystem"
  56319. * @returns a string containing the class name
  56320. */
  56321. ParticleSystem.prototype.getClassName = function () {
  56322. return "ParticleSystem";
  56323. };
  56324. ParticleSystem.prototype._createIndexBuffer = function () {
  56325. var indices = [];
  56326. var index = 0;
  56327. for (var count = 0; count < this._capacity; count++) {
  56328. indices.push(index);
  56329. indices.push(index + 1);
  56330. indices.push(index + 2);
  56331. indices.push(index);
  56332. indices.push(index + 2);
  56333. indices.push(index + 3);
  56334. index += 4;
  56335. }
  56336. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56337. };
  56338. /**
  56339. * Gets the maximum number of particles active at the same time.
  56340. * @returns The max number of active particles.
  56341. */
  56342. ParticleSystem.prototype.getCapacity = function () {
  56343. return this._capacity;
  56344. };
  56345. /**
  56346. * Gets Wether there are still active particles in the system.
  56347. * @returns True if it is alive, otherwise false.
  56348. */
  56349. ParticleSystem.prototype.isAlive = function () {
  56350. return this._alive;
  56351. };
  56352. /**
  56353. * Gets Wether the system has been started.
  56354. * @returns True if it has been started, otherwise false.
  56355. */
  56356. ParticleSystem.prototype.isStarted = function () {
  56357. return this._started;
  56358. };
  56359. /**
  56360. * Starts the particle system and begins to emit.
  56361. */
  56362. ParticleSystem.prototype.start = function () {
  56363. this._started = true;
  56364. this._stopped = false;
  56365. this._actualFrame = 0;
  56366. if (this.subEmitters && this.subEmitters.length != 0) {
  56367. this.activeSubSystems = new Array();
  56368. }
  56369. };
  56370. /**
  56371. * Stops the particle system.
  56372. * @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.
  56373. */
  56374. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56375. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56376. this._stopped = true;
  56377. if (stopSubEmitters) {
  56378. this._stopSubEmitters();
  56379. }
  56380. };
  56381. // animation sheet
  56382. /**
  56383. * Remove all active particles
  56384. */
  56385. ParticleSystem.prototype.reset = function () {
  56386. this._stockParticles = [];
  56387. this._particles = [];
  56388. };
  56389. /**
  56390. * @hidden (for internal use only)
  56391. */
  56392. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56393. var offset = index * this._vertexBufferSize;
  56394. this._vertexData[offset] = particle.position.x;
  56395. this._vertexData[offset + 1] = particle.position.y;
  56396. this._vertexData[offset + 2] = particle.position.z;
  56397. this._vertexData[offset + 3] = particle.color.r;
  56398. this._vertexData[offset + 4] = particle.color.g;
  56399. this._vertexData[offset + 5] = particle.color.b;
  56400. this._vertexData[offset + 6] = particle.color.a;
  56401. this._vertexData[offset + 7] = particle.angle;
  56402. this._vertexData[offset + 8] = particle.size;
  56403. this._vertexData[offset + 9] = offsetX;
  56404. this._vertexData[offset + 10] = offsetY;
  56405. };
  56406. /**
  56407. * @hidden (for internal use only)
  56408. */
  56409. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56410. if (offsetX === 0)
  56411. offsetX = this._epsilon;
  56412. else if (offsetX === 1)
  56413. offsetX = 1 - this._epsilon;
  56414. if (offsetY === 0)
  56415. offsetY = this._epsilon;
  56416. else if (offsetY === 1)
  56417. offsetY = 1 - this._epsilon;
  56418. var offset = index * this._vertexBufferSize;
  56419. this._vertexData[offset] = particle.position.x;
  56420. this._vertexData[offset + 1] = particle.position.y;
  56421. this._vertexData[offset + 2] = particle.position.z;
  56422. this._vertexData[offset + 3] = particle.color.r;
  56423. this._vertexData[offset + 4] = particle.color.g;
  56424. this._vertexData[offset + 5] = particle.color.b;
  56425. this._vertexData[offset + 6] = particle.color.a;
  56426. this._vertexData[offset + 7] = particle.angle;
  56427. this._vertexData[offset + 8] = particle.size;
  56428. this._vertexData[offset + 9] = offsetX;
  56429. this._vertexData[offset + 10] = offsetY;
  56430. this._vertexData[offset + 11] = particle.cellIndex;
  56431. };
  56432. ParticleSystem.prototype._stopSubEmitters = function () {
  56433. if (!this.activeSubSystems) {
  56434. return;
  56435. }
  56436. this.activeSubSystems.forEach(function (subSystem) {
  56437. subSystem.stop(true);
  56438. });
  56439. this.activeSubSystems = new Array();
  56440. };
  56441. ParticleSystem.prototype._removeFromRoot = function () {
  56442. if (!this._rootParticleSystem) {
  56443. return;
  56444. }
  56445. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56446. if (index !== -1) {
  56447. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56448. }
  56449. };
  56450. // end of sub system methods
  56451. ParticleSystem.prototype._update = function (newParticles) {
  56452. // Update current
  56453. this._alive = this._particles.length > 0;
  56454. this.updateFunction(this._particles);
  56455. // Add new ones
  56456. var worldMatrix;
  56457. if (this.emitter.position) {
  56458. var emitterMesh = this.emitter;
  56459. worldMatrix = emitterMesh.getWorldMatrix();
  56460. }
  56461. else {
  56462. var emitterPosition = this.emitter;
  56463. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56464. }
  56465. var particle;
  56466. for (var index = 0; index < newParticles; index++) {
  56467. if (this._particles.length === this._capacity) {
  56468. break;
  56469. }
  56470. particle = this._createParticle();
  56471. this._particles.push(particle);
  56472. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56473. if (this.startPositionFunction) {
  56474. this.startPositionFunction(worldMatrix, particle.position, particle);
  56475. }
  56476. else {
  56477. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56478. }
  56479. if (this.startDirectionFunction) {
  56480. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56481. }
  56482. else {
  56483. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56484. }
  56485. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56486. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56487. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56488. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56489. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56490. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56491. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56492. }
  56493. };
  56494. ParticleSystem.prototype._getEffect = function () {
  56495. if (this._customEffect) {
  56496. return this._customEffect;
  56497. }
  56498. ;
  56499. var defines = [];
  56500. if (this._scene.clipPlane) {
  56501. defines.push("#define CLIPPLANE");
  56502. }
  56503. if (this._isAnimationSheetEnabled) {
  56504. defines.push("#define ANIMATESHEET");
  56505. }
  56506. // Effect
  56507. var join = defines.join("\n");
  56508. if (this._cachedDefines !== join) {
  56509. this._cachedDefines = join;
  56510. var attributesNamesOrOptions;
  56511. var effectCreationOption;
  56512. if (this._isAnimationSheetEnabled) {
  56513. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56514. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56515. }
  56516. else {
  56517. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56518. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56519. }
  56520. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56521. }
  56522. return this._effect;
  56523. };
  56524. /**
  56525. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56526. */
  56527. ParticleSystem.prototype.animate = function () {
  56528. if (!this._started)
  56529. return;
  56530. var effect = this._getEffect();
  56531. // Check
  56532. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56533. return;
  56534. if (this._currentRenderId === this._scene.getRenderId()) {
  56535. return;
  56536. }
  56537. this._currentRenderId = this._scene.getRenderId();
  56538. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56539. // determine the number of particles we need to create
  56540. var newParticles;
  56541. if (this.manualEmitCount > -1) {
  56542. newParticles = this.manualEmitCount;
  56543. this._newPartsExcess = 0;
  56544. this.manualEmitCount = 0;
  56545. }
  56546. else {
  56547. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56548. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56549. }
  56550. if (this._newPartsExcess > 1.0) {
  56551. newParticles += this._newPartsExcess >> 0;
  56552. this._newPartsExcess -= this._newPartsExcess >> 0;
  56553. }
  56554. this._alive = false;
  56555. if (!this._stopped) {
  56556. this._actualFrame += this._scaledUpdateSpeed;
  56557. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56558. this.stop();
  56559. }
  56560. else {
  56561. newParticles = 0;
  56562. }
  56563. this._update(newParticles);
  56564. // Stopped?
  56565. if (this._stopped) {
  56566. if (!this._alive) {
  56567. this._started = false;
  56568. if (this.onAnimationEnd) {
  56569. this.onAnimationEnd();
  56570. }
  56571. if (this.disposeOnStop) {
  56572. this._scene._toBeDisposed.push(this);
  56573. }
  56574. }
  56575. }
  56576. // Animation sheet
  56577. if (this._isAnimationSheetEnabled) {
  56578. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56579. }
  56580. else {
  56581. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56582. }
  56583. // Update VBO
  56584. var offset = 0;
  56585. for (var index = 0; index < this._particles.length; index++) {
  56586. var particle = this._particles[index];
  56587. this._appendParticleVertexes(offset, particle);
  56588. offset += 4;
  56589. }
  56590. if (this._vertexBuffer) {
  56591. this._vertexBuffer.update(this._vertexData);
  56592. }
  56593. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56594. this.stop();
  56595. }
  56596. };
  56597. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56598. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56599. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56600. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56601. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56602. };
  56603. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56604. this._appendParticleVertex(offset++, particle, 0, 0);
  56605. this._appendParticleVertex(offset++, particle, 1, 0);
  56606. this._appendParticleVertex(offset++, particle, 1, 1);
  56607. this._appendParticleVertex(offset++, particle, 0, 1);
  56608. };
  56609. /**
  56610. * Rebuilds the particle system.
  56611. */
  56612. ParticleSystem.prototype.rebuild = function () {
  56613. this._createIndexBuffer();
  56614. if (this._vertexBuffer) {
  56615. this._vertexBuffer._rebuild();
  56616. }
  56617. };
  56618. /**
  56619. * Is this system ready to be used/rendered
  56620. * @return true if the system is ready
  56621. */
  56622. ParticleSystem.prototype.isReady = function () {
  56623. var effect = this._getEffect();
  56624. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56625. return false;
  56626. }
  56627. return true;
  56628. };
  56629. /**
  56630. * Renders the particle system in its current state.
  56631. * @returns the current number of particles
  56632. */
  56633. ParticleSystem.prototype.render = function () {
  56634. var effect = this._getEffect();
  56635. // Check
  56636. if (!this.isReady() || !this._particles.length) {
  56637. return 0;
  56638. }
  56639. var engine = this._scene.getEngine();
  56640. // Render
  56641. engine.enableEffect(effect);
  56642. engine.setState(false);
  56643. var viewMatrix = this._scene.getViewMatrix();
  56644. effect.setTexture("diffuseSampler", this.particleTexture);
  56645. effect.setMatrix("view", viewMatrix);
  56646. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56647. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56648. var baseSize = this.particleTexture.getBaseSize();
  56649. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56650. }
  56651. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56652. if (this._scene.clipPlane) {
  56653. var clipPlane = this._scene.clipPlane;
  56654. var invView = viewMatrix.clone();
  56655. invView.invert();
  56656. effect.setMatrix("invView", invView);
  56657. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56658. }
  56659. // VBOs
  56660. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56661. // Draw order
  56662. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56663. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56664. }
  56665. else {
  56666. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56667. }
  56668. if (this.forceDepthWrite) {
  56669. engine.setDepthWrite(true);
  56670. }
  56671. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56672. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56673. return this._particles.length;
  56674. };
  56675. /**
  56676. * Disposes the particle system and free the associated resources
  56677. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56678. */
  56679. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56680. if (disposeTexture === void 0) { disposeTexture = true; }
  56681. if (this._vertexBuffer) {
  56682. this._vertexBuffer.dispose();
  56683. this._vertexBuffer = null;
  56684. }
  56685. if (this._indexBuffer) {
  56686. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56687. this._indexBuffer = null;
  56688. }
  56689. if (disposeTexture && this.particleTexture) {
  56690. this.particleTexture.dispose();
  56691. this.particleTexture = null;
  56692. }
  56693. this._removeFromRoot();
  56694. // Remove from scene
  56695. var index = this._scene.particleSystems.indexOf(this);
  56696. if (index > -1) {
  56697. this._scene.particleSystems.splice(index, 1);
  56698. }
  56699. // Callback
  56700. this.onDisposeObservable.notifyObservers(this);
  56701. this.onDisposeObservable.clear();
  56702. };
  56703. /**
  56704. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56705. * @param radius The radius of the sphere to emit from
  56706. * @returns the emitter
  56707. */
  56708. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56709. if (radius === void 0) { radius = 1; }
  56710. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56711. this.particleEmitterType = particleEmitter;
  56712. return particleEmitter;
  56713. };
  56714. /**
  56715. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56716. * @param radius The radius of the sphere to emit from
  56717. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56718. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56719. * @returns the emitter
  56720. */
  56721. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56722. if (radius === void 0) { radius = 1; }
  56723. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56724. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56725. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56726. this.particleEmitterType = particleEmitter;
  56727. return particleEmitter;
  56728. };
  56729. /**
  56730. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56731. * @param radius The radius of the cone to emit from
  56732. * @param angle The base angle of the cone
  56733. * @returns the emitter
  56734. */
  56735. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56736. if (radius === void 0) { radius = 1; }
  56737. if (angle === void 0) { angle = Math.PI / 4; }
  56738. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56739. this.particleEmitterType = particleEmitter;
  56740. return particleEmitter;
  56741. };
  56742. // 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.
  56743. /**
  56744. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56745. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56746. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56747. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56748. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56749. * @returns the emitter
  56750. */
  56751. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56752. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56753. this.particleEmitterType = particleEmitter;
  56754. this.direction1 = direction1;
  56755. this.direction2 = direction2;
  56756. this.minEmitBox = minEmitBox;
  56757. this.maxEmitBox = maxEmitBox;
  56758. return particleEmitter;
  56759. };
  56760. // Clone
  56761. /**
  56762. * Clones the particle system.
  56763. * @param name The name of the cloned object
  56764. * @param newEmitter The new emitter to use
  56765. * @returns the cloned particle system
  56766. */
  56767. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56768. var custom = null;
  56769. var program = null;
  56770. if (this.customShader != null) {
  56771. program = this.customShader;
  56772. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56773. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56774. }
  56775. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56776. result.customShader = program;
  56777. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56778. if (newEmitter === undefined) {
  56779. newEmitter = this.emitter;
  56780. }
  56781. result.emitter = newEmitter;
  56782. if (this.particleTexture) {
  56783. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56784. }
  56785. if (!this.preventAutoStart) {
  56786. result.start();
  56787. }
  56788. return result;
  56789. };
  56790. /**
  56791. * Serializes the particle system to a JSON object.
  56792. * @returns the JSON object
  56793. */
  56794. ParticleSystem.prototype.serialize = function () {
  56795. var serializationObject = {};
  56796. serializationObject.name = this.name;
  56797. serializationObject.id = this.id;
  56798. // Emitter
  56799. if (this.emitter.position) {
  56800. var emitterMesh = this.emitter;
  56801. serializationObject.emitterId = emitterMesh.id;
  56802. }
  56803. else {
  56804. var emitterPosition = this.emitter;
  56805. serializationObject.emitter = emitterPosition.asArray();
  56806. }
  56807. serializationObject.capacity = this.getCapacity();
  56808. if (this.particleTexture) {
  56809. serializationObject.textureName = this.particleTexture.name;
  56810. }
  56811. // Animations
  56812. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56813. // Particle system
  56814. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56815. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56816. serializationObject.minSize = this.minSize;
  56817. serializationObject.maxSize = this.maxSize;
  56818. serializationObject.minEmitPower = this.minEmitPower;
  56819. serializationObject.maxEmitPower = this.maxEmitPower;
  56820. serializationObject.minLifeTime = this.minLifeTime;
  56821. serializationObject.maxLifeTime = this.maxLifeTime;
  56822. serializationObject.emitRate = this.emitRate;
  56823. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56824. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56825. serializationObject.gravity = this.gravity.asArray();
  56826. serializationObject.direction1 = this.direction1.asArray();
  56827. serializationObject.direction2 = this.direction2.asArray();
  56828. serializationObject.color1 = this.color1.asArray();
  56829. serializationObject.color2 = this.color2.asArray();
  56830. serializationObject.colorDead = this.colorDead.asArray();
  56831. serializationObject.updateSpeed = this.updateSpeed;
  56832. serializationObject.targetStopDuration = this.targetStopDuration;
  56833. serializationObject.textureMask = this.textureMask.asArray();
  56834. serializationObject.blendMode = this.blendMode;
  56835. serializationObject.customShader = this.customShader;
  56836. serializationObject.preventAutoStart = this.preventAutoStart;
  56837. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56838. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56839. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56840. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56841. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56842. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56843. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56844. // Emitter
  56845. if (this.particleEmitterType) {
  56846. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56847. }
  56848. return serializationObject;
  56849. };
  56850. /**
  56851. * Parses a JSON object to create a particle system.
  56852. * @param parsedParticleSystem The JSON object to parse
  56853. * @param scene The scene to create the particle system in
  56854. * @param rootUrl The root url to use to load external dependencies like texture
  56855. * @returns the Parsed particle system
  56856. */
  56857. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56858. var name = parsedParticleSystem.name;
  56859. var custom = null;
  56860. var program = null;
  56861. if (parsedParticleSystem.customShader) {
  56862. program = parsedParticleSystem.customShader;
  56863. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56864. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56865. }
  56866. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56867. particleSystem.customShader = program;
  56868. if (parsedParticleSystem.id) {
  56869. particleSystem.id = parsedParticleSystem.id;
  56870. }
  56871. // Auto start
  56872. if (parsedParticleSystem.preventAutoStart) {
  56873. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56874. }
  56875. // Texture
  56876. if (parsedParticleSystem.textureName) {
  56877. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56878. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56879. }
  56880. // Emitter
  56881. if (parsedParticleSystem.emitterId) {
  56882. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56883. }
  56884. else {
  56885. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56886. }
  56887. // Animations
  56888. if (parsedParticleSystem.animations) {
  56889. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56890. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56891. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56892. }
  56893. }
  56894. if (parsedParticleSystem.autoAnimate) {
  56895. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56896. }
  56897. // Particle system
  56898. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56899. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56900. particleSystem.minSize = parsedParticleSystem.minSize;
  56901. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56902. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56903. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56904. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56905. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56906. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56907. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56908. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56909. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56910. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56911. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56912. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56913. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56914. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56915. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56916. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56917. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56918. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56919. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56920. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56921. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56922. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56923. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56924. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56925. if (!particleSystem.preventAutoStart) {
  56926. particleSystem.start();
  56927. }
  56928. return particleSystem;
  56929. };
  56930. /**
  56931. * Source color is added to the destination color without alpha affecting the result.
  56932. */
  56933. ParticleSystem.BLENDMODE_ONEONE = 0;
  56934. /**
  56935. * Blend current color and particle color using particle’s alpha.
  56936. */
  56937. ParticleSystem.BLENDMODE_STANDARD = 1;
  56938. return ParticleSystem;
  56939. }());
  56940. BABYLON.ParticleSystem = ParticleSystem;
  56941. })(BABYLON || (BABYLON = {}));
  56942. //# sourceMappingURL=babylon.particleSystem.js.map
  56943. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56944. var BABYLON;
  56945. (function (BABYLON) {
  56946. /**
  56947. * Particle emitter emitting particles from the inside of a box.
  56948. * It emits the particles randomly between 2 given directions.
  56949. */
  56950. var BoxParticleEmitter = /** @class */ (function () {
  56951. /**
  56952. * Creates a new instance BoxParticleEmitter
  56953. */
  56954. function BoxParticleEmitter() {
  56955. /**
  56956. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56957. */
  56958. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56959. /**
  56960. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56961. */
  56962. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56963. /**
  56964. * 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.
  56965. */
  56966. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56967. /**
  56968. * 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.
  56969. */
  56970. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56971. }
  56972. /**
  56973. * Called by the particle System when the direction is computed for the created particle.
  56974. * @param emitPower is the power of the particle (speed)
  56975. * @param worldMatrix is the world matrix of the particle system
  56976. * @param directionToUpdate is the direction vector to update with the result
  56977. * @param particle is the particle we are computed the direction for
  56978. */
  56979. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56980. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56981. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56982. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56983. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56984. };
  56985. /**
  56986. * Called by the particle System when the position is computed for the created particle.
  56987. * @param worldMatrix is the world matrix of the particle system
  56988. * @param positionToUpdate is the position vector to update with the result
  56989. * @param particle is the particle we are computed the position for
  56990. */
  56991. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56992. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56993. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56994. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56995. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56996. };
  56997. /**
  56998. * Clones the current emitter and returns a copy of it
  56999. * @returns the new emitter
  57000. */
  57001. BoxParticleEmitter.prototype.clone = function () {
  57002. var newOne = new BoxParticleEmitter();
  57003. BABYLON.Tools.DeepCopy(this, newOne);
  57004. return newOne;
  57005. };
  57006. /**
  57007. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57008. * @param effect defines the update shader
  57009. */
  57010. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57011. effect.setVector3("direction1", this.direction1);
  57012. effect.setVector3("direction2", this.direction2);
  57013. effect.setVector3("minEmitBox", this.minEmitBox);
  57014. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57015. };
  57016. /**
  57017. * Returns a string to use to update the GPU particles update shader
  57018. * @returns a string containng the defines string
  57019. */
  57020. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57021. return "#define BOXEMITTER";
  57022. };
  57023. /**
  57024. * Returns the string "BoxEmitter"
  57025. * @returns a string containing the class name
  57026. */
  57027. BoxParticleEmitter.prototype.getClassName = function () {
  57028. return "BoxEmitter";
  57029. };
  57030. /**
  57031. * Serializes the particle system to a JSON object.
  57032. * @returns the JSON object
  57033. */
  57034. BoxParticleEmitter.prototype.serialize = function () {
  57035. var serializationObject = {};
  57036. serializationObject.type = this.getClassName();
  57037. serializationObject.direction1 = this.direction1.asArray();
  57038. serializationObject.direction2 = this.direction2.asArray();
  57039. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57040. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57041. return serializationObject;
  57042. };
  57043. /**
  57044. * Parse properties from a JSON object
  57045. * @param serializationObject defines the JSON object
  57046. */
  57047. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57048. this.direction1.copyFrom(serializationObject.direction1);
  57049. this.direction2.copyFrom(serializationObject.direction2);
  57050. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  57051. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  57052. };
  57053. return BoxParticleEmitter;
  57054. }());
  57055. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57056. })(BABYLON || (BABYLON = {}));
  57057. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57058. var BABYLON;
  57059. (function (BABYLON) {
  57060. /**
  57061. * Particle emitter emitting particles from the inside of a cone.
  57062. * It emits the particles alongside the cone volume from the base to the particle.
  57063. * The emission direction might be randomized.
  57064. */
  57065. var ConeParticleEmitter = /** @class */ (function () {
  57066. /**
  57067. * Creates a new instance ConeParticleEmitter
  57068. * @param radius the radius of the emission cone (1 by default)
  57069. * @param angles the cone base angle (PI by default)
  57070. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57071. */
  57072. function ConeParticleEmitter(radius,
  57073. /**
  57074. * The radius of the emission cone.
  57075. */
  57076. angle,
  57077. /**
  57078. * The cone base angle.
  57079. */
  57080. directionRandomizer) {
  57081. if (radius === void 0) { radius = 1; }
  57082. if (angle === void 0) { angle = Math.PI; }
  57083. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57084. this.angle = angle;
  57085. this.directionRandomizer = directionRandomizer;
  57086. this.radius = radius;
  57087. }
  57088. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57089. /**
  57090. * Gets the radius of the emission cone.
  57091. */
  57092. get: function () {
  57093. return this._radius;
  57094. },
  57095. /**
  57096. * Sets the radius of the emission cone.
  57097. */
  57098. set: function (value) {
  57099. this._radius = value;
  57100. if (this.angle !== 0) {
  57101. this._height = value / Math.tan(this.angle / 2);
  57102. }
  57103. else {
  57104. this._height = 1;
  57105. }
  57106. },
  57107. enumerable: true,
  57108. configurable: true
  57109. });
  57110. /**
  57111. * Called by the particle System when the direction is computed for the created particle.
  57112. * @param emitPower is the power of the particle (speed)
  57113. * @param worldMatrix is the world matrix of the particle system
  57114. * @param directionToUpdate is the direction vector to update with the result
  57115. * @param particle is the particle we are computed the direction for
  57116. */
  57117. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57118. if (this.angle === 0) {
  57119. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57120. }
  57121. else {
  57122. // measure the direction Vector from the emitter to the particle.
  57123. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57124. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57125. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57126. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57127. direction.x += randX;
  57128. direction.y += randY;
  57129. direction.z += randZ;
  57130. direction.normalize();
  57131. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57132. }
  57133. };
  57134. /**
  57135. * Called by the particle System when the position is computed for the created particle.
  57136. * @param worldMatrix is the world matrix of the particle system
  57137. * @param positionToUpdate is the position vector to update with the result
  57138. * @param particle is the particle we are computed the position for
  57139. */
  57140. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57141. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57142. var h = BABYLON.Scalar.RandomRange(0, 1);
  57143. // Better distribution in a cone at normal angles.
  57144. h = 1 - h * h;
  57145. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57146. radius = radius * h;
  57147. var randX = radius * Math.sin(s);
  57148. var randZ = radius * Math.cos(s);
  57149. var randY = h * this._height;
  57150. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57151. };
  57152. /**
  57153. * Clones the current emitter and returns a copy of it
  57154. * @returns the new emitter
  57155. */
  57156. ConeParticleEmitter.prototype.clone = function () {
  57157. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  57158. BABYLON.Tools.DeepCopy(this, newOne);
  57159. return newOne;
  57160. };
  57161. /**
  57162. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57163. * @param effect defines the update shader
  57164. */
  57165. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57166. effect.setFloat("radius", this.radius);
  57167. effect.setFloat("coneAngle", this.angle);
  57168. effect.setFloat("height", this._height);
  57169. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57170. };
  57171. /**
  57172. * Returns a string to use to update the GPU particles update shader
  57173. * @returns a string containng the defines string
  57174. */
  57175. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57176. return "#define CONEEMITTER";
  57177. };
  57178. /**
  57179. * Returns the string "BoxEmitter"
  57180. * @returns a string containing the class name
  57181. */
  57182. ConeParticleEmitter.prototype.getClassName = function () {
  57183. return "ConeEmitter";
  57184. };
  57185. /**
  57186. * Serializes the particle system to a JSON object.
  57187. * @returns the JSON object
  57188. */
  57189. ConeParticleEmitter.prototype.serialize = function () {
  57190. var serializationObject = {};
  57191. serializationObject.type = this.getClassName();
  57192. serializationObject.radius = this.radius;
  57193. serializationObject.angle = this.angle;
  57194. serializationObject.directionRandomizer = this.directionRandomizer;
  57195. return serializationObject;
  57196. };
  57197. /**
  57198. * Parse properties from a JSON object
  57199. * @param serializationObject defines the JSON object
  57200. */
  57201. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57202. this.radius = serializationObject.radius;
  57203. this.angle = serializationObject.angle;
  57204. this.directionRandomizer = serializationObject.directionRandomizer;
  57205. };
  57206. return ConeParticleEmitter;
  57207. }());
  57208. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57209. })(BABYLON || (BABYLON = {}));
  57210. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57211. var BABYLON;
  57212. (function (BABYLON) {
  57213. /**
  57214. * Particle emitter emitting particles from the inside of a sphere.
  57215. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57216. */
  57217. var SphereParticleEmitter = /** @class */ (function () {
  57218. /**
  57219. * Creates a new instance SphereParticleEmitter
  57220. * @param radius the radius of the emission sphere (1 by default)
  57221. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57222. */
  57223. function SphereParticleEmitter(
  57224. /**
  57225. * The radius of the emission sphere.
  57226. */
  57227. radius,
  57228. /**
  57229. * How much to randomize the particle direction [0-1].
  57230. */
  57231. directionRandomizer) {
  57232. if (radius === void 0) { radius = 1; }
  57233. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57234. this.radius = radius;
  57235. this.directionRandomizer = directionRandomizer;
  57236. }
  57237. /**
  57238. * Called by the particle System when the direction is computed for the created particle.
  57239. * @param emitPower is the power of the particle (speed)
  57240. * @param worldMatrix is the world matrix of the particle system
  57241. * @param directionToUpdate is the direction vector to update with the result
  57242. * @param particle is the particle we are computed the direction for
  57243. */
  57244. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57245. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57246. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57247. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57248. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57249. direction.x += randX;
  57250. direction.y += randY;
  57251. direction.z += randZ;
  57252. direction.normalize();
  57253. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57254. };
  57255. /**
  57256. * Called by the particle System when the position is computed for the created particle.
  57257. * @param worldMatrix is the world matrix of the particle system
  57258. * @param positionToUpdate is the position vector to update with the result
  57259. * @param particle is the particle we are computed the position for
  57260. */
  57261. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57262. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57263. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57264. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57265. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57266. var randY = randRadius * Math.cos(theta);
  57267. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57268. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57269. };
  57270. /**
  57271. * Clones the current emitter and returns a copy of it
  57272. * @returns the new emitter
  57273. */
  57274. SphereParticleEmitter.prototype.clone = function () {
  57275. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57276. BABYLON.Tools.DeepCopy(this, newOne);
  57277. return newOne;
  57278. };
  57279. /**
  57280. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57281. * @param effect defines the update shader
  57282. */
  57283. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57284. effect.setFloat("radius", this.radius);
  57285. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57286. };
  57287. /**
  57288. * Returns a string to use to update the GPU particles update shader
  57289. * @returns a string containng the defines string
  57290. */
  57291. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57292. return "#define SPHEREEMITTER";
  57293. };
  57294. /**
  57295. * Returns the string "SphereParticleEmitter"
  57296. * @returns a string containing the class name
  57297. */
  57298. SphereParticleEmitter.prototype.getClassName = function () {
  57299. return "SphereParticleEmitter";
  57300. };
  57301. /**
  57302. * Serializes the particle system to a JSON object.
  57303. * @returns the JSON object
  57304. */
  57305. SphereParticleEmitter.prototype.serialize = function () {
  57306. var serializationObject = {};
  57307. serializationObject.type = this.getClassName();
  57308. serializationObject.radius = this.radius;
  57309. serializationObject.directionRandomizer = this.directionRandomizer;
  57310. return serializationObject;
  57311. };
  57312. /**
  57313. * Parse properties from a JSON object
  57314. * @param serializationObject defines the JSON object
  57315. */
  57316. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57317. this.radius = serializationObject.radius;
  57318. this.directionRandomizer = serializationObject.directionRandomizer;
  57319. };
  57320. return SphereParticleEmitter;
  57321. }());
  57322. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57323. /**
  57324. * Particle emitter emitting particles from the inside of a sphere.
  57325. * It emits the particles randomly between two vectors.
  57326. */
  57327. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57328. __extends(SphereDirectedParticleEmitter, _super);
  57329. /**
  57330. * Creates a new instance SphereDirectedParticleEmitter
  57331. * @param radius the radius of the emission sphere (1 by default)
  57332. * @param direction1 the min limit of the emission direction (up vector by default)
  57333. * @param direction2 the max limit of the emission direction (up vector by default)
  57334. */
  57335. function SphereDirectedParticleEmitter(radius,
  57336. /**
  57337. * The min limit of the emission direction.
  57338. */
  57339. direction1,
  57340. /**
  57341. * The max limit of the emission direction.
  57342. */
  57343. direction2) {
  57344. if (radius === void 0) { radius = 1; }
  57345. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57346. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57347. var _this = _super.call(this, radius) || this;
  57348. _this.direction1 = direction1;
  57349. _this.direction2 = direction2;
  57350. return _this;
  57351. }
  57352. /**
  57353. * Called by the particle System when the direction is computed for the created particle.
  57354. * @param emitPower is the power of the particle (speed)
  57355. * @param worldMatrix is the world matrix of the particle system
  57356. * @param directionToUpdate is the direction vector to update with the result
  57357. * @param particle is the particle we are computed the direction for
  57358. */
  57359. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57360. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57361. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57362. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57363. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57364. };
  57365. /**
  57366. * Clones the current emitter and returns a copy of it
  57367. * @returns the new emitter
  57368. */
  57369. SphereDirectedParticleEmitter.prototype.clone = function () {
  57370. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57371. BABYLON.Tools.DeepCopy(this, newOne);
  57372. return newOne;
  57373. };
  57374. /**
  57375. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57376. * @param effect defines the update shader
  57377. */
  57378. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57379. effect.setFloat("radius", this.radius);
  57380. effect.setVector3("direction1", this.direction1);
  57381. effect.setVector3("direction2", this.direction2);
  57382. };
  57383. /**
  57384. * Returns a string to use to update the GPU particles update shader
  57385. * @returns a string containng the defines string
  57386. */
  57387. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57388. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57389. };
  57390. /**
  57391. * Returns the string "SphereDirectedParticleEmitter"
  57392. * @returns a string containing the class name
  57393. */
  57394. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57395. return "SphereDirectedParticleEmitter";
  57396. };
  57397. /**
  57398. * Serializes the particle system to a JSON object.
  57399. * @returns the JSON object
  57400. */
  57401. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57402. var serializationObject = _super.prototype.serialize.call(this);
  57403. serializationObject.direction1 = this.direction1.asArray();
  57404. serializationObject.direction2 = this.direction2.asArray();
  57405. return serializationObject;
  57406. };
  57407. /**
  57408. * Parse properties from a JSON object
  57409. * @param serializationObject defines the JSON object
  57410. */
  57411. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57412. _super.prototype.parse.call(this, serializationObject);
  57413. this.direction1.copyFrom(serializationObject.direction1);
  57414. this.direction2.copyFrom(serializationObject.direction2);
  57415. };
  57416. return SphereDirectedParticleEmitter;
  57417. }(SphereParticleEmitter));
  57418. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57419. })(BABYLON || (BABYLON = {}));
  57420. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57421. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57422. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57423. s = arguments[i];
  57424. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57425. t[p] = s[p];
  57426. }
  57427. return t;
  57428. };
  57429. var BABYLON;
  57430. (function (BABYLON) {
  57431. /**
  57432. * This represents a GPU particle system in Babylon
  57433. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57434. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57435. */
  57436. var GPUParticleSystem = /** @class */ (function () {
  57437. /**
  57438. * Instantiates a GPU particle system.
  57439. * 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.
  57440. * @param name The name of the particle system
  57441. * @param capacity The max number of particles alive at the same time
  57442. * @param scene The scene the particle system belongs to
  57443. */
  57444. function GPUParticleSystem(name, options, scene) {
  57445. /**
  57446. * The emitter represents the Mesh or position we are attaching the particle system to.
  57447. */
  57448. this.emitter = null;
  57449. /**
  57450. * The rendering group used by the Particle system to chose when to render.
  57451. */
  57452. this.renderingGroupId = 0;
  57453. /**
  57454. * The layer mask we are rendering the particles through.
  57455. */
  57456. this.layerMask = 0x0FFFFFFF;
  57457. this._targetIndex = 0;
  57458. this._currentRenderId = -1;
  57459. this._started = false;
  57460. this._stopped = false;
  57461. this._timeDelta = 0;
  57462. this._attributesStrideSize = 16;
  57463. this._actualFrame = 0;
  57464. /**
  57465. * List of animations used by the particle system.
  57466. */
  57467. this.animations = [];
  57468. /**
  57469. * An event triggered when the system is disposed.
  57470. */
  57471. this.onDisposeObservable = new BABYLON.Observable();
  57472. /**
  57473. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57474. */
  57475. this.updateSpeed = 0.01;
  57476. /**
  57477. * The amount of time the particle system is running (depends of the overall update speed).
  57478. */
  57479. this.targetStopDuration = 0;
  57480. /**
  57481. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57482. */
  57483. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57484. /**
  57485. * Minimum life time of emitting particles.
  57486. */
  57487. this.minLifeTime = 1;
  57488. /**
  57489. * Maximum life time of emitting particles.
  57490. */
  57491. this.maxLifeTime = 1;
  57492. /**
  57493. * Minimum Size of emitting particles.
  57494. */
  57495. this.minSize = 1;
  57496. /**
  57497. * Maximum Size of emitting particles.
  57498. */
  57499. this.maxSize = 1;
  57500. /**
  57501. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57502. */
  57503. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57504. /**
  57505. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57506. */
  57507. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57508. /**
  57509. * Color the particle will have at the end of its lifetime.
  57510. */
  57511. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57512. /**
  57513. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57514. */
  57515. this.emitRate = 100;
  57516. /**
  57517. * You can use gravity if you want to give an orientation to your particles.
  57518. */
  57519. this.gravity = BABYLON.Vector3.Zero();
  57520. /**
  57521. * Minimum power of emitting particles.
  57522. */
  57523. this.minEmitPower = 1;
  57524. /**
  57525. * Maximum power of emitting particles.
  57526. */
  57527. this.maxEmitPower = 1;
  57528. /**
  57529. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57530. */
  57531. this.minAngularSpeed = 0;
  57532. /**
  57533. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57534. */
  57535. this.maxAngularSpeed = 0;
  57536. /**
  57537. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57538. * to override the particles.
  57539. */
  57540. this.forceDepthWrite = false;
  57541. this.id = name;
  57542. this.name = name;
  57543. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57544. this._engine = this._scene.getEngine();
  57545. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57546. this._capacity = fullOptions.capacity;
  57547. this._activeCount = fullOptions.capacity;
  57548. this._currentActiveCount = 0;
  57549. this._scene.particleSystems.push(this);
  57550. this._updateEffectOptions = {
  57551. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  57552. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57553. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57554. "angleRange"],
  57555. uniformBuffersNames: [],
  57556. samplers: ["randomSampler"],
  57557. defines: "",
  57558. fallbacks: null,
  57559. onCompiled: null,
  57560. onError: null,
  57561. indexParameters: null,
  57562. maxSimultaneousLights: 0,
  57563. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  57564. };
  57565. // Random data
  57566. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57567. var d = [];
  57568. for (var i = 0; i < maxTextureSize; ++i) {
  57569. d.push(Math.random());
  57570. d.push(Math.random());
  57571. d.push(Math.random());
  57572. d.push(Math.random());
  57573. }
  57574. 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);
  57575. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57576. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57577. this._randomTextureSize = maxTextureSize;
  57578. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57579. }
  57580. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57581. /**
  57582. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57583. */
  57584. get: function () {
  57585. if (!BABYLON.Engine.LastCreatedEngine) {
  57586. return false;
  57587. }
  57588. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57589. },
  57590. enumerable: true,
  57591. configurable: true
  57592. });
  57593. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57594. /**
  57595. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57596. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57597. */
  57598. get: function () {
  57599. if (this.particleEmitterType.direction1) {
  57600. return this.particleEmitterType.direction1;
  57601. }
  57602. return BABYLON.Vector3.Zero();
  57603. },
  57604. set: function (value) {
  57605. if (this.particleEmitterType.direction1) {
  57606. this.particleEmitterType.direction1 = value;
  57607. }
  57608. },
  57609. enumerable: true,
  57610. configurable: true
  57611. });
  57612. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57613. /**
  57614. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57615. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57616. */
  57617. get: function () {
  57618. if (this.particleEmitterType.direction2) {
  57619. return this.particleEmitterType.direction2;
  57620. }
  57621. return BABYLON.Vector3.Zero();
  57622. },
  57623. set: function (value) {
  57624. if (this.particleEmitterType.direction2) {
  57625. this.particleEmitterType.direction2 = value;
  57626. }
  57627. },
  57628. enumerable: true,
  57629. configurable: true
  57630. });
  57631. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57632. /**
  57633. * 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.
  57634. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57635. */
  57636. get: function () {
  57637. if (this.particleEmitterType.minEmitBox) {
  57638. return this.particleEmitterType.minEmitBox;
  57639. }
  57640. return BABYLON.Vector3.Zero();
  57641. },
  57642. set: function (value) {
  57643. if (this.particleEmitterType.minEmitBox) {
  57644. this.particleEmitterType.minEmitBox = value;
  57645. }
  57646. },
  57647. enumerable: true,
  57648. configurable: true
  57649. });
  57650. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57651. /**
  57652. * 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.
  57653. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57654. */
  57655. get: function () {
  57656. if (this.particleEmitterType.maxEmitBox) {
  57657. return this.particleEmitterType.maxEmitBox;
  57658. }
  57659. return BABYLON.Vector3.Zero();
  57660. },
  57661. set: function (value) {
  57662. if (this.particleEmitterType.maxEmitBox) {
  57663. this.particleEmitterType.maxEmitBox = value;
  57664. }
  57665. },
  57666. enumerable: true,
  57667. configurable: true
  57668. });
  57669. /**
  57670. * Gets the maximum number of particles active at the same time.
  57671. * @returns The max number of active particles.
  57672. */
  57673. GPUParticleSystem.prototype.getCapacity = function () {
  57674. return this._capacity;
  57675. };
  57676. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57677. /**
  57678. * Gets or set the number of active particles
  57679. */
  57680. get: function () {
  57681. return this._activeCount;
  57682. },
  57683. set: function (value) {
  57684. this._activeCount = Math.min(value, this._capacity);
  57685. },
  57686. enumerable: true,
  57687. configurable: true
  57688. });
  57689. /**
  57690. * Is this system ready to be used/rendered
  57691. * @return true if the system is ready
  57692. */
  57693. GPUParticleSystem.prototype.isReady = function () {
  57694. if (!this._updateEffect) {
  57695. this._recreateUpdateEffect();
  57696. this._recreateRenderEffect();
  57697. return false;
  57698. }
  57699. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57700. return false;
  57701. }
  57702. return true;
  57703. };
  57704. /**
  57705. * Gets Wether the system has been started.
  57706. * @returns True if it has been started, otherwise false.
  57707. */
  57708. GPUParticleSystem.prototype.isStarted = function () {
  57709. return this._started;
  57710. };
  57711. /**
  57712. * Starts the particle system and begins to emit.
  57713. */
  57714. GPUParticleSystem.prototype.start = function () {
  57715. this._started = true;
  57716. this._stopped = false;
  57717. };
  57718. /**
  57719. * Stops the particle system.
  57720. */
  57721. GPUParticleSystem.prototype.stop = function () {
  57722. this._stopped = true;
  57723. };
  57724. /**
  57725. * Remove all active particles
  57726. */
  57727. GPUParticleSystem.prototype.reset = function () {
  57728. this._releaseBuffers();
  57729. this._releaseVAOs();
  57730. this._currentActiveCount = 0;
  57731. this._targetIndex = 0;
  57732. };
  57733. /**
  57734. * Returns the string "GPUParticleSystem"
  57735. * @returns a string containing the class name
  57736. */
  57737. GPUParticleSystem.prototype.getClassName = function () {
  57738. return "GPUParticleSystem";
  57739. };
  57740. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57741. var updateVertexBuffers = {};
  57742. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57743. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57744. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57745. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57746. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57747. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57748. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57749. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2);
  57750. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57751. this._engine.bindArrayBuffer(null);
  57752. return vao;
  57753. };
  57754. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57755. var renderVertexBuffers = {};
  57756. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57757. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57758. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57759. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57760. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57761. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2, this._attributesStrideSize, true);
  57762. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57763. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57764. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57765. this._engine.bindArrayBuffer(null);
  57766. return vao;
  57767. };
  57768. GPUParticleSystem.prototype._initialize = function (force) {
  57769. if (force === void 0) { force = false; }
  57770. if (this._buffer0 && !force) {
  57771. return;
  57772. }
  57773. var engine = this._scene.getEngine();
  57774. var data = new Array();
  57775. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57776. // position
  57777. data.push(0.0);
  57778. data.push(0.0);
  57779. data.push(0.0);
  57780. // Age and life
  57781. data.push(0.0); // create the particle as a dead one to create a new one at start
  57782. data.push(0.0);
  57783. // Seed
  57784. data.push(Math.random());
  57785. // Size
  57786. data.push(0.0);
  57787. // color
  57788. data.push(0.0);
  57789. data.push(0.0);
  57790. data.push(0.0);
  57791. data.push(0.0);
  57792. // direction
  57793. data.push(0.0);
  57794. data.push(0.0);
  57795. data.push(0.0);
  57796. // angle
  57797. data.push(0.0);
  57798. data.push(0.0);
  57799. }
  57800. // Sprite data
  57801. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57802. -0.5, 0.5, 0, 1,
  57803. -0.5, -0.5, 0, 0,
  57804. 0.5, -0.5, 1, 0]);
  57805. // Buffers
  57806. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57807. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57808. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57809. // Update VAO
  57810. this._updateVAO = [];
  57811. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57812. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57813. // Render VAO
  57814. this._renderVAO = [];
  57815. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57816. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57817. // Links
  57818. this._sourceBuffer = this._buffer0;
  57819. this._targetBuffer = this._buffer1;
  57820. };
  57821. /** @hidden */
  57822. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57823. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57824. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57825. return;
  57826. }
  57827. this._updateEffectOptions.defines = defines;
  57828. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57829. };
  57830. /** @hidden */
  57831. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57832. var defines = "";
  57833. if (this._scene.clipPlane) {
  57834. defines = "\n#define CLIPPLANE";
  57835. }
  57836. if (this._renderEffect && this._renderEffect.defines === defines) {
  57837. return;
  57838. }
  57839. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57840. };
  57841. /**
  57842. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57843. */
  57844. GPUParticleSystem.prototype.animate = function () {
  57845. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57846. this._actualFrame += this._timeDelta;
  57847. if (!this._stopped) {
  57848. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57849. this.stop();
  57850. }
  57851. }
  57852. };
  57853. /**
  57854. * Renders the particle system in its current state.
  57855. * @returns the current number of particles
  57856. */
  57857. GPUParticleSystem.prototype.render = function () {
  57858. if (!this._started) {
  57859. return 0;
  57860. }
  57861. this._recreateUpdateEffect();
  57862. this._recreateRenderEffect();
  57863. if (!this.isReady()) {
  57864. return 0;
  57865. }
  57866. if (this._currentRenderId === this._scene.getRenderId()) {
  57867. return 0;
  57868. }
  57869. this._currentRenderId = this._scene.getRenderId();
  57870. // Get everything ready to render
  57871. this._initialize();
  57872. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57873. // Enable update effect
  57874. this._engine.enableEffect(this._updateEffect);
  57875. this._engine.setState(false);
  57876. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57877. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57878. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57879. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57880. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57881. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57882. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57883. this._updateEffect.setDirectColor4("color1", this.color1);
  57884. this._updateEffect.setDirectColor4("color2", this.color2);
  57885. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57886. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  57887. this._updateEffect.setVector3("gravity", this.gravity);
  57888. if (this.particleEmitterType) {
  57889. this.particleEmitterType.applyToShader(this._updateEffect);
  57890. }
  57891. var emitterWM;
  57892. if (this.emitter.position) {
  57893. var emitterMesh = this.emitter;
  57894. emitterWM = emitterMesh.getWorldMatrix();
  57895. }
  57896. else {
  57897. var emitterPosition = this.emitter;
  57898. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57899. }
  57900. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57901. // Bind source VAO
  57902. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57903. // Update
  57904. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57905. this._engine.setRasterizerState(false);
  57906. this._engine.beginTransformFeedback();
  57907. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57908. this._engine.endTransformFeedback();
  57909. this._engine.setRasterizerState(true);
  57910. this._engine.bindTransformFeedbackBuffer(null);
  57911. // Enable render effect
  57912. this._engine.enableEffect(this._renderEffect);
  57913. var viewMatrix = this._scene.getViewMatrix();
  57914. this._renderEffect.setMatrix("view", viewMatrix);
  57915. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57916. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57917. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57918. if (this._scene.clipPlane) {
  57919. var clipPlane = this._scene.clipPlane;
  57920. var invView = viewMatrix.clone();
  57921. invView.invert();
  57922. this._renderEffect.setMatrix("invView", invView);
  57923. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57924. }
  57925. // Draw order
  57926. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57927. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57928. }
  57929. else {
  57930. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57931. }
  57932. if (this.forceDepthWrite) {
  57933. this._engine.setDepthWrite(true);
  57934. }
  57935. // Bind source VAO
  57936. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57937. // Render
  57938. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57939. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57940. // Switch VAOs
  57941. this._targetIndex++;
  57942. if (this._targetIndex === 2) {
  57943. this._targetIndex = 0;
  57944. }
  57945. // Switch buffers
  57946. var tmpBuffer = this._sourceBuffer;
  57947. this._sourceBuffer = this._targetBuffer;
  57948. this._targetBuffer = tmpBuffer;
  57949. return this._currentActiveCount;
  57950. };
  57951. /**
  57952. * Rebuilds the particle system
  57953. */
  57954. GPUParticleSystem.prototype.rebuild = function () {
  57955. this._initialize(true);
  57956. };
  57957. GPUParticleSystem.prototype._releaseBuffers = function () {
  57958. if (this._buffer0) {
  57959. this._buffer0.dispose();
  57960. this._buffer0 = null;
  57961. }
  57962. if (this._buffer1) {
  57963. this._buffer1.dispose();
  57964. this._buffer1 = null;
  57965. }
  57966. if (this._spriteBuffer) {
  57967. this._spriteBuffer.dispose();
  57968. this._spriteBuffer = null;
  57969. }
  57970. };
  57971. GPUParticleSystem.prototype._releaseVAOs = function () {
  57972. if (!this._updateVAO) {
  57973. return;
  57974. }
  57975. for (var index = 0; index < this._updateVAO.length; index++) {
  57976. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57977. }
  57978. this._updateVAO = [];
  57979. for (var index = 0; index < this._renderVAO.length; index++) {
  57980. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57981. }
  57982. this._renderVAO = [];
  57983. };
  57984. /**
  57985. * Disposes the particle system and free the associated resources
  57986. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57987. */
  57988. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57989. if (disposeTexture === void 0) { disposeTexture = true; }
  57990. var index = this._scene.particleSystems.indexOf(this);
  57991. if (index > -1) {
  57992. this._scene.particleSystems.splice(index, 1);
  57993. }
  57994. this._releaseBuffers();
  57995. this._releaseVAOs();
  57996. if (this._randomTexture) {
  57997. this._randomTexture.dispose();
  57998. this._randomTexture = null;
  57999. }
  58000. if (disposeTexture && this.particleTexture) {
  58001. this.particleTexture.dispose();
  58002. this.particleTexture = null;
  58003. }
  58004. // Callback
  58005. this.onDisposeObservable.notifyObservers(this);
  58006. this.onDisposeObservable.clear();
  58007. };
  58008. /**
  58009. * Clones the particle system.
  58010. * @param name The name of the cloned object
  58011. * @param newEmitter The new emitter to use
  58012. * @returns the cloned particle system
  58013. */
  58014. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58015. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58016. BABYLON.Tools.DeepCopy(this, result);
  58017. if (newEmitter === undefined) {
  58018. newEmitter = this.emitter;
  58019. }
  58020. result.emitter = newEmitter;
  58021. if (this.particleTexture) {
  58022. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58023. }
  58024. return result;
  58025. };
  58026. /**
  58027. * Serializes the particle system to a JSON object.
  58028. * @returns the JSON object
  58029. */
  58030. GPUParticleSystem.prototype.serialize = function () {
  58031. var serializationObject = {};
  58032. serializationObject.name = this.name;
  58033. serializationObject.id = this.id;
  58034. // Emitter
  58035. if (this.emitter.position) {
  58036. var emitterMesh = this.emitter;
  58037. serializationObject.emitterId = emitterMesh.id;
  58038. }
  58039. else {
  58040. var emitterPosition = this.emitter;
  58041. serializationObject.emitter = emitterPosition.asArray();
  58042. }
  58043. serializationObject.capacity = this.getCapacity();
  58044. if (this.particleTexture) {
  58045. serializationObject.textureName = this.particleTexture.name;
  58046. }
  58047. // Animations
  58048. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  58049. // Particle system
  58050. serializationObject.activeParticleCount = this.activeParticleCount;
  58051. serializationObject.randomTextureSize = this._randomTextureSize;
  58052. serializationObject.minSize = this.minSize;
  58053. serializationObject.maxSize = this.maxSize;
  58054. serializationObject.minEmitPower = this.minEmitPower;
  58055. serializationObject.maxEmitPower = this.maxEmitPower;
  58056. serializationObject.minLifeTime = this.minLifeTime;
  58057. serializationObject.maxLifeTime = this.maxLifeTime;
  58058. serializationObject.minAngularSpeed = this.minAngularSpeed;
  58059. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  58060. serializationObject.emitRate = this.emitRate;
  58061. serializationObject.gravity = this.gravity.asArray();
  58062. serializationObject.color1 = this.color1.asArray();
  58063. serializationObject.color2 = this.color2.asArray();
  58064. serializationObject.colorDead = this.colorDead.asArray();
  58065. serializationObject.updateSpeed = this.updateSpeed;
  58066. serializationObject.targetStopDuration = this.targetStopDuration;
  58067. serializationObject.blendMode = this.blendMode;
  58068. // Emitter
  58069. if (this.particleEmitterType) {
  58070. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  58071. }
  58072. return serializationObject;
  58073. };
  58074. /**
  58075. * Parses a JSON object to create a GPU particle system.
  58076. * @param parsedParticleSystem The JSON object to parse
  58077. * @param scene The scene to create the particle system in
  58078. * @param rootUrl The root url to use to load external dependencies like texture
  58079. * @returns the parsed GPU particle system
  58080. */
  58081. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58082. var name = parsedParticleSystem.name;
  58083. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58084. if (parsedParticleSystem.id) {
  58085. particleSystem.id = parsedParticleSystem.id;
  58086. }
  58087. // Texture
  58088. if (parsedParticleSystem.textureName) {
  58089. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58090. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58091. }
  58092. // Emitter
  58093. if (parsedParticleSystem.emitterId) {
  58094. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58095. }
  58096. else {
  58097. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58098. }
  58099. // Animations
  58100. if (parsedParticleSystem.animations) {
  58101. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58102. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58103. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58104. }
  58105. }
  58106. // Particle system
  58107. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58108. particleSystem.minSize = parsedParticleSystem.minSize;
  58109. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58110. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58111. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58112. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58113. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58114. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58115. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58116. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58117. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58118. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58119. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58120. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58121. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58122. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58123. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58124. // Emitter
  58125. if (parsedParticleSystem.particleEmitterType) {
  58126. var emitterType = void 0;
  58127. switch (parsedParticleSystem.particleEmitterType.type) {
  58128. case "SphereEmitter":
  58129. emitterType = new BABYLON.SphereParticleEmitter();
  58130. break;
  58131. case "SphereDirectedParticleEmitter":
  58132. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58133. break;
  58134. case "ConeEmitter":
  58135. emitterType = new BABYLON.ConeParticleEmitter();
  58136. break;
  58137. case "BoxEmitter":
  58138. default:
  58139. emitterType = new BABYLON.BoxParticleEmitter();
  58140. break;
  58141. }
  58142. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58143. particleSystem.particleEmitterType = emitterType;
  58144. }
  58145. return particleSystem;
  58146. };
  58147. return GPUParticleSystem;
  58148. }());
  58149. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58150. })(BABYLON || (BABYLON = {}));
  58151. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58152. var BABYLON;
  58153. (function (BABYLON) {
  58154. /**
  58155. * Represents one particle of a solid particle system.
  58156. */
  58157. var SolidParticle = /** @class */ (function () {
  58158. /**
  58159. * Creates a Solid Particle object.
  58160. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58161. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58162. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58163. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58164. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58165. * @param shapeId (integer) is the model shape identifier in the SPS.
  58166. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58167. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58168. */
  58169. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58170. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58171. /**
  58172. * particle global index
  58173. */
  58174. this.idx = 0;
  58175. /**
  58176. * The color of the particle
  58177. */
  58178. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58179. /**
  58180. * The world space position of the particle.
  58181. */
  58182. this.position = BABYLON.Vector3.Zero();
  58183. /**
  58184. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58185. */
  58186. this.rotation = BABYLON.Vector3.Zero();
  58187. /**
  58188. * The scaling of the particle.
  58189. */
  58190. this.scaling = BABYLON.Vector3.One();
  58191. /**
  58192. * The uvs of the particle.
  58193. */
  58194. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58195. /**
  58196. * The current speed of the particle.
  58197. */
  58198. this.velocity = BABYLON.Vector3.Zero();
  58199. /**
  58200. * The pivot point in the particle local space.
  58201. */
  58202. this.pivot = BABYLON.Vector3.Zero();
  58203. /**
  58204. * Must the particle be translated from its pivot point in its local space ?
  58205. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58206. * Default : false
  58207. */
  58208. this.translateFromPivot = false;
  58209. /**
  58210. * Is the particle active or not ?
  58211. */
  58212. this.alive = true;
  58213. /**
  58214. * Is the particle visible or not ?
  58215. */
  58216. this.isVisible = true;
  58217. /**
  58218. * Index of this particle in the global "positions" array (Internal use)
  58219. */
  58220. this._pos = 0;
  58221. /**
  58222. * Index of this particle in the global "indices" array (Internal use)
  58223. */
  58224. this._ind = 0;
  58225. /**
  58226. * ModelShape id of this particle
  58227. */
  58228. this.shapeId = 0;
  58229. /**
  58230. * Index of the particle in its shape id (Internal use)
  58231. */
  58232. this.idxInShape = 0;
  58233. /**
  58234. * Still set as invisible in order to skip useless computations (Internal use)
  58235. */
  58236. this._stillInvisible = false;
  58237. /**
  58238. * Last computed particle rotation matrix
  58239. */
  58240. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58241. /**
  58242. * Parent particle Id, if any.
  58243. * Default null.
  58244. */
  58245. this.parentId = null;
  58246. /**
  58247. * Internal global position in the SPS.
  58248. */
  58249. this._globalPosition = BABYLON.Vector3.Zero();
  58250. this.idx = particleIndex;
  58251. this._pos = positionIndex;
  58252. this._ind = indiceIndex;
  58253. this._model = model;
  58254. this.shapeId = shapeId;
  58255. this.idxInShape = idxInShape;
  58256. this._sps = sps;
  58257. if (modelBoundingInfo) {
  58258. this._modelBoundingInfo = modelBoundingInfo;
  58259. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58260. }
  58261. }
  58262. Object.defineProperty(SolidParticle.prototype, "scale", {
  58263. /**
  58264. * Legacy support, changed scale to scaling
  58265. */
  58266. get: function () {
  58267. return this.scaling;
  58268. },
  58269. /**
  58270. * Legacy support, changed scale to scaling
  58271. */
  58272. set: function (scale) {
  58273. this.scaling = scale;
  58274. },
  58275. enumerable: true,
  58276. configurable: true
  58277. });
  58278. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58279. /**
  58280. * Legacy support, changed quaternion to rotationQuaternion
  58281. */
  58282. get: function () {
  58283. return this.rotationQuaternion;
  58284. },
  58285. /**
  58286. * Legacy support, changed quaternion to rotationQuaternion
  58287. */
  58288. set: function (q) {
  58289. this.rotationQuaternion = q;
  58290. },
  58291. enumerable: true,
  58292. configurable: true
  58293. });
  58294. /**
  58295. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58296. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58297. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58298. * @returns true if it intersects
  58299. */
  58300. SolidParticle.prototype.intersectsMesh = function (target) {
  58301. if (!this._boundingInfo || !target._boundingInfo) {
  58302. return false;
  58303. }
  58304. if (this._sps._bSphereOnly) {
  58305. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58306. }
  58307. return this._boundingInfo.intersects(target._boundingInfo, false);
  58308. };
  58309. return SolidParticle;
  58310. }());
  58311. BABYLON.SolidParticle = SolidParticle;
  58312. /**
  58313. * Represents the shape of the model used by one particle of a solid particle system.
  58314. * SPS internal tool, don't use it manually.
  58315. */
  58316. var ModelShape = /** @class */ (function () {
  58317. /**
  58318. * 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.
  58319. * SPS internal tool, don't use it manually.
  58320. * @hidden
  58321. */
  58322. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58323. /**
  58324. * length of the shape in the model indices array (internal use)
  58325. */
  58326. this._indicesLength = 0;
  58327. this.shapeID = id;
  58328. this._shape = shape;
  58329. this._indicesLength = indicesLength;
  58330. this._shapeUV = shapeUV;
  58331. this._positionFunction = posFunction;
  58332. this._vertexFunction = vtxFunction;
  58333. }
  58334. return ModelShape;
  58335. }());
  58336. BABYLON.ModelShape = ModelShape;
  58337. /**
  58338. * Represents a Depth Sorted Particle in the solid particle system.
  58339. */
  58340. var DepthSortedParticle = /** @class */ (function () {
  58341. function DepthSortedParticle() {
  58342. /**
  58343. * Index of the particle in the "indices" array
  58344. */
  58345. this.ind = 0;
  58346. /**
  58347. * Length of the particle shape in the "indices" array
  58348. */
  58349. this.indicesLength = 0;
  58350. /**
  58351. * Squared distance from the particle to the camera
  58352. */
  58353. this.sqDistance = 0.0;
  58354. }
  58355. return DepthSortedParticle;
  58356. }());
  58357. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58358. })(BABYLON || (BABYLON = {}));
  58359. //# sourceMappingURL=babylon.solidParticle.js.map
  58360. var BABYLON;
  58361. (function (BABYLON) {
  58362. /**
  58363. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58364. *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.
  58365. * The SPS is also a particle system. It provides some methods to manage the particles.
  58366. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58367. *
  58368. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58369. */
  58370. var SolidParticleSystem = /** @class */ (function () {
  58371. /**
  58372. * Creates a SPS (Solid Particle System) object.
  58373. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58374. * @param scene (Scene) is the scene in which the SPS is added.
  58375. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58376. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58377. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58378. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58379. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58380. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58381. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58382. */
  58383. function SolidParticleSystem(name, scene, options) {
  58384. /**
  58385. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58386. * Example : var p = SPS.particles[i];
  58387. */
  58388. this.particles = new Array();
  58389. /**
  58390. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58391. */
  58392. this.nbParticles = 0;
  58393. /**
  58394. * If the particles must ever face the camera (default false). Useful for planar particles.
  58395. */
  58396. this.billboard = false;
  58397. /**
  58398. * Recompute normals when adding a shape
  58399. */
  58400. this.recomputeNormals = true;
  58401. /**
  58402. * This a counter ofr your own usage. It's not set by any SPS functions.
  58403. */
  58404. this.counter = 0;
  58405. /**
  58406. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58407. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58408. */
  58409. this.vars = {};
  58410. /**
  58411. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58412. */
  58413. this._bSphereOnly = false;
  58414. /**
  58415. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58416. */
  58417. this._bSphereRadiusFactor = 1.0;
  58418. this._positions = new Array();
  58419. this._indices = new Array();
  58420. this._normals = new Array();
  58421. this._colors = new Array();
  58422. this._uvs = new Array();
  58423. this._index = 0; // indices index
  58424. this._updatable = true;
  58425. this._pickable = false;
  58426. this._isVisibilityBoxLocked = false;
  58427. this._alwaysVisible = false;
  58428. this._depthSort = false;
  58429. this._shapeCounter = 0;
  58430. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58431. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58432. this._computeParticleColor = true;
  58433. this._computeParticleTexture = true;
  58434. this._computeParticleRotation = true;
  58435. this._computeParticleVertex = false;
  58436. this._computeBoundingBox = false;
  58437. this._depthSortParticles = true;
  58438. this._cam_axisZ = BABYLON.Vector3.Zero();
  58439. this._cam_axisY = BABYLON.Vector3.Zero();
  58440. this._cam_axisX = BABYLON.Vector3.Zero();
  58441. this._axisZ = BABYLON.Axis.Z;
  58442. this._camDir = BABYLON.Vector3.Zero();
  58443. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58444. this._rotMatrix = new BABYLON.Matrix();
  58445. this._invertMatrix = new BABYLON.Matrix();
  58446. this._rotated = BABYLON.Vector3.Zero();
  58447. this._quaternion = new BABYLON.Quaternion();
  58448. this._vertex = BABYLON.Vector3.Zero();
  58449. this._normal = BABYLON.Vector3.Zero();
  58450. this._yaw = 0.0;
  58451. this._pitch = 0.0;
  58452. this._roll = 0.0;
  58453. this._halfroll = 0.0;
  58454. this._halfpitch = 0.0;
  58455. this._halfyaw = 0.0;
  58456. this._sinRoll = 0.0;
  58457. this._cosRoll = 0.0;
  58458. this._sinPitch = 0.0;
  58459. this._cosPitch = 0.0;
  58460. this._sinYaw = 0.0;
  58461. this._cosYaw = 0.0;
  58462. this._mustUnrotateFixedNormals = false;
  58463. this._minimum = BABYLON.Vector3.Zero();
  58464. this._maximum = BABYLON.Vector3.Zero();
  58465. this._minBbox = BABYLON.Vector3.Zero();
  58466. this._maxBbox = BABYLON.Vector3.Zero();
  58467. this._particlesIntersect = false;
  58468. this._depthSortFunction = function (p1, p2) {
  58469. return (p2.sqDistance - p1.sqDistance);
  58470. };
  58471. this._needs32Bits = false;
  58472. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58473. this._scaledPivot = BABYLON.Vector3.Zero();
  58474. this._particleHasParent = false;
  58475. this.name = name;
  58476. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58477. this._camera = scene.activeCamera;
  58478. this._pickable = options ? options.isPickable : false;
  58479. this._depthSort = options ? options.enableDepthSort : false;
  58480. this._particlesIntersect = options ? options.particleIntersection : false;
  58481. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58482. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58483. if (options && options.updatable) {
  58484. this._updatable = options.updatable;
  58485. }
  58486. else {
  58487. this._updatable = true;
  58488. }
  58489. if (this._pickable) {
  58490. this.pickedParticles = [];
  58491. }
  58492. if (this._depthSort) {
  58493. this.depthSortedParticles = [];
  58494. }
  58495. }
  58496. /**
  58497. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58498. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58499. * @returns the created mesh
  58500. */
  58501. SolidParticleSystem.prototype.buildMesh = function () {
  58502. if (this.nbParticles === 0) {
  58503. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58504. this.addShape(triangle, 1);
  58505. triangle.dispose();
  58506. }
  58507. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58508. this._positions32 = new Float32Array(this._positions);
  58509. this._uvs32 = new Float32Array(this._uvs);
  58510. this._colors32 = new Float32Array(this._colors);
  58511. if (this.recomputeNormals) {
  58512. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58513. }
  58514. this._normals32 = new Float32Array(this._normals);
  58515. this._fixedNormal32 = new Float32Array(this._normals);
  58516. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58517. this._unrotateFixedNormals();
  58518. }
  58519. var vertexData = new BABYLON.VertexData();
  58520. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58521. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58522. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58523. if (this._uvs32.length > 0) {
  58524. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58525. }
  58526. if (this._colors32.length > 0) {
  58527. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58528. }
  58529. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58530. vertexData.applyToMesh(mesh, this._updatable);
  58531. this.mesh = mesh;
  58532. this.mesh.isPickable = this._pickable;
  58533. // free memory
  58534. if (!this._depthSort) {
  58535. this._indices = null;
  58536. }
  58537. this._positions = null;
  58538. this._normals = null;
  58539. this._uvs = null;
  58540. this._colors = null;
  58541. if (!this._updatable) {
  58542. this.particles.length = 0;
  58543. }
  58544. return mesh;
  58545. };
  58546. /**
  58547. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58548. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58549. * Thus the particles generated from `digest()` have their property `position` set yet.
  58550. * @param mesh ( Mesh ) is the mesh to be digested
  58551. * @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
  58552. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58553. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58554. * @returns the current SPS
  58555. */
  58556. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58557. var size = (options && options.facetNb) || 1;
  58558. var number = (options && options.number) || 0;
  58559. var delta = (options && options.delta) || 0;
  58560. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58561. var meshInd = mesh.getIndices();
  58562. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58563. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58564. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58565. var f = 0; // facet counter
  58566. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58567. // compute size from number
  58568. if (number) {
  58569. number = (number > totalFacets) ? totalFacets : number;
  58570. size = Math.round(totalFacets / number);
  58571. delta = 0;
  58572. }
  58573. else {
  58574. size = (size > totalFacets) ? totalFacets : size;
  58575. }
  58576. var facetPos = []; // submesh positions
  58577. var facetInd = []; // submesh indices
  58578. var facetUV = []; // submesh UV
  58579. var facetCol = []; // submesh colors
  58580. var barycenter = BABYLON.Vector3.Zero();
  58581. var sizeO = size;
  58582. while (f < totalFacets) {
  58583. size = sizeO + Math.floor((1 + delta) * Math.random());
  58584. if (f > totalFacets - size) {
  58585. size = totalFacets - f;
  58586. }
  58587. // reset temp arrays
  58588. facetPos.length = 0;
  58589. facetInd.length = 0;
  58590. facetUV.length = 0;
  58591. facetCol.length = 0;
  58592. // iterate over "size" facets
  58593. var fi = 0;
  58594. for (var j = f * 3; j < (f + size) * 3; j++) {
  58595. facetInd.push(fi);
  58596. var i = meshInd[j];
  58597. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58598. if (meshUV) {
  58599. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58600. }
  58601. if (meshCol) {
  58602. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58603. }
  58604. fi++;
  58605. }
  58606. // create a model shape for each single particle
  58607. var idx = this.nbParticles;
  58608. var shape = this._posToShape(facetPos);
  58609. var shapeUV = this._uvsToShapeUV(facetUV);
  58610. // compute the barycenter of the shape
  58611. var v;
  58612. for (v = 0; v < shape.length; v++) {
  58613. barycenter.addInPlace(shape[v]);
  58614. }
  58615. barycenter.scaleInPlace(1 / shape.length);
  58616. // shift the shape from its barycenter to the origin
  58617. for (v = 0; v < shape.length; v++) {
  58618. shape[v].subtractInPlace(barycenter);
  58619. }
  58620. var bInfo;
  58621. if (this._particlesIntersect) {
  58622. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58623. }
  58624. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58625. // add the particle in the SPS
  58626. var currentPos = this._positions.length;
  58627. var currentInd = this._indices.length;
  58628. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58629. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58630. // initialize the particle position
  58631. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58632. this._index += shape.length;
  58633. idx++;
  58634. this.nbParticles++;
  58635. this._shapeCounter++;
  58636. f += size;
  58637. }
  58638. return this;
  58639. };
  58640. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58641. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58642. var index = 0;
  58643. var idx = 0;
  58644. for (var p = 0; p < this.particles.length; p++) {
  58645. this._particle = this.particles[p];
  58646. this._shape = this._particle._model._shape;
  58647. if (this._particle.rotationQuaternion) {
  58648. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58649. }
  58650. else {
  58651. this._yaw = this._particle.rotation.y;
  58652. this._pitch = this._particle.rotation.x;
  58653. this._roll = this._particle.rotation.z;
  58654. this._quaternionRotationYPR();
  58655. }
  58656. this._quaternionToRotationMatrix();
  58657. this._rotMatrix.invertToRef(this._invertMatrix);
  58658. for (var pt = 0; pt < this._shape.length; pt++) {
  58659. idx = index + pt * 3;
  58660. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58661. this._fixedNormal32[idx] = this._normal.x;
  58662. this._fixedNormal32[idx + 1] = this._normal.y;
  58663. this._fixedNormal32[idx + 2] = this._normal.z;
  58664. }
  58665. index = idx + 3;
  58666. }
  58667. };
  58668. //reset copy
  58669. SolidParticleSystem.prototype._resetCopy = function () {
  58670. this._copy.position.x = 0;
  58671. this._copy.position.y = 0;
  58672. this._copy.position.z = 0;
  58673. this._copy.rotation.x = 0;
  58674. this._copy.rotation.y = 0;
  58675. this._copy.rotation.z = 0;
  58676. this._copy.rotationQuaternion = null;
  58677. this._copy.scaling.x = 1.0;
  58678. this._copy.scaling.y = 1.0;
  58679. this._copy.scaling.z = 1.0;
  58680. this._copy.uvs.x = 0;
  58681. this._copy.uvs.y = 0;
  58682. this._copy.uvs.z = 1.0;
  58683. this._copy.uvs.w = 1.0;
  58684. this._copy.color = null;
  58685. this._copy.translateFromPivot = false;
  58686. };
  58687. // _meshBuilder : inserts the shape model in the global SPS mesh
  58688. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58689. var i;
  58690. var u = 0;
  58691. var c = 0;
  58692. var n = 0;
  58693. this._resetCopy();
  58694. if (options && options.positionFunction) { // call to custom positionFunction
  58695. options.positionFunction(this._copy, idx, idxInShape);
  58696. this._mustUnrotateFixedNormals = true;
  58697. }
  58698. if (this._copy.rotationQuaternion) {
  58699. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58700. }
  58701. else {
  58702. this._yaw = this._copy.rotation.y;
  58703. this._pitch = this._copy.rotation.x;
  58704. this._roll = this._copy.rotation.z;
  58705. this._quaternionRotationYPR();
  58706. }
  58707. this._quaternionToRotationMatrix();
  58708. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58709. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58710. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58711. if (this._copy.translateFromPivot) {
  58712. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58713. }
  58714. else {
  58715. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58716. }
  58717. for (i = 0; i < shape.length; i++) {
  58718. this._vertex.x = shape[i].x;
  58719. this._vertex.y = shape[i].y;
  58720. this._vertex.z = shape[i].z;
  58721. if (options && options.vertexFunction) {
  58722. options.vertexFunction(this._copy, this._vertex, i);
  58723. }
  58724. this._vertex.x *= this._copy.scaling.x;
  58725. this._vertex.y *= this._copy.scaling.y;
  58726. this._vertex.z *= this._copy.scaling.z;
  58727. this._vertex.x -= this._scaledPivot.x;
  58728. this._vertex.y -= this._scaledPivot.y;
  58729. this._vertex.z -= this._scaledPivot.z;
  58730. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58731. this._rotated.addInPlace(this._pivotBackTranslation);
  58732. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58733. if (meshUV) {
  58734. 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);
  58735. u += 2;
  58736. }
  58737. if (this._copy.color) {
  58738. this._color = this._copy.color;
  58739. }
  58740. else if (meshCol && meshCol[c] !== undefined) {
  58741. this._color.r = meshCol[c];
  58742. this._color.g = meshCol[c + 1];
  58743. this._color.b = meshCol[c + 2];
  58744. this._color.a = meshCol[c + 3];
  58745. }
  58746. else {
  58747. this._color.r = 1.0;
  58748. this._color.g = 1.0;
  58749. this._color.b = 1.0;
  58750. this._color.a = 1.0;
  58751. }
  58752. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58753. c += 4;
  58754. if (!this.recomputeNormals && meshNor) {
  58755. this._normal.x = meshNor[n];
  58756. this._normal.y = meshNor[n + 1];
  58757. this._normal.z = meshNor[n + 2];
  58758. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58759. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58760. n += 3;
  58761. }
  58762. }
  58763. for (i = 0; i < meshInd.length; i++) {
  58764. var current_ind = p + meshInd[i];
  58765. indices.push(current_ind);
  58766. if (current_ind > 65535) {
  58767. this._needs32Bits = true;
  58768. }
  58769. }
  58770. if (this._pickable) {
  58771. var nbfaces = meshInd.length / 3;
  58772. for (i = 0; i < nbfaces; i++) {
  58773. this.pickedParticles.push({ idx: idx, faceId: i });
  58774. }
  58775. }
  58776. if (this._depthSort) {
  58777. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58778. }
  58779. return this._copy;
  58780. };
  58781. // returns a shape array from positions array
  58782. SolidParticleSystem.prototype._posToShape = function (positions) {
  58783. var shape = [];
  58784. for (var i = 0; i < positions.length; i += 3) {
  58785. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58786. }
  58787. return shape;
  58788. };
  58789. // returns a shapeUV array from a Vector4 uvs
  58790. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58791. var shapeUV = [];
  58792. if (uvs) {
  58793. for (var i = 0; i < uvs.length; i++)
  58794. shapeUV.push(uvs[i]);
  58795. }
  58796. return shapeUV;
  58797. };
  58798. // adds a new particle object in the particles array
  58799. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58800. if (bInfo === void 0) { bInfo = null; }
  58801. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58802. this.particles.push(sp);
  58803. return sp;
  58804. };
  58805. /**
  58806. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58807. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58808. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58809. * @param nb (positive integer) the number of particles to be created from this model
  58810. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58811. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58812. * @returns the number of shapes in the system
  58813. */
  58814. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58815. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58816. var meshInd = mesh.getIndices();
  58817. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58818. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58819. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58820. var bbInfo;
  58821. if (this._particlesIntersect) {
  58822. bbInfo = mesh.getBoundingInfo();
  58823. }
  58824. var shape = this._posToShape(meshPos);
  58825. var shapeUV = this._uvsToShapeUV(meshUV);
  58826. var posfunc = options ? options.positionFunction : null;
  58827. var vtxfunc = options ? options.vertexFunction : null;
  58828. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58829. // particles
  58830. var sp;
  58831. var currentCopy;
  58832. var idx = this.nbParticles;
  58833. for (var i = 0; i < nb; i++) {
  58834. var currentPos = this._positions.length;
  58835. var currentInd = this._indices.length;
  58836. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58837. if (this._updatable) {
  58838. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58839. sp.position.copyFrom(currentCopy.position);
  58840. sp.rotation.copyFrom(currentCopy.rotation);
  58841. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58842. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58843. }
  58844. if (currentCopy.color && sp.color) {
  58845. sp.color.copyFrom(currentCopy.color);
  58846. }
  58847. sp.scaling.copyFrom(currentCopy.scaling);
  58848. sp.uvs.copyFrom(currentCopy.uvs);
  58849. }
  58850. this._index += shape.length;
  58851. idx++;
  58852. }
  58853. this.nbParticles += nb;
  58854. this._shapeCounter++;
  58855. return this._shapeCounter - 1;
  58856. };
  58857. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58858. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58859. this._resetCopy();
  58860. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58861. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58862. }
  58863. if (this._copy.rotationQuaternion) {
  58864. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58865. }
  58866. else {
  58867. this._yaw = this._copy.rotation.y;
  58868. this._pitch = this._copy.rotation.x;
  58869. this._roll = this._copy.rotation.z;
  58870. this._quaternionRotationYPR();
  58871. }
  58872. this._quaternionToRotationMatrix();
  58873. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58874. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58875. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58876. if (this._copy.translateFromPivot) {
  58877. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58878. }
  58879. else {
  58880. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58881. }
  58882. this._shape = particle._model._shape;
  58883. for (var pt = 0; pt < this._shape.length; pt++) {
  58884. this._vertex.x = this._shape[pt].x;
  58885. this._vertex.y = this._shape[pt].y;
  58886. this._vertex.z = this._shape[pt].z;
  58887. if (particle._model._vertexFunction) {
  58888. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58889. }
  58890. this._vertex.x *= this._copy.scaling.x;
  58891. this._vertex.y *= this._copy.scaling.y;
  58892. this._vertex.z *= this._copy.scaling.z;
  58893. this._vertex.x -= this._scaledPivot.x;
  58894. this._vertex.y -= this._scaledPivot.y;
  58895. this._vertex.z -= this._scaledPivot.z;
  58896. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58897. this._rotated.addInPlace(this._pivotBackTranslation);
  58898. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58899. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58900. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58901. }
  58902. particle.position.x = 0.0;
  58903. particle.position.y = 0.0;
  58904. particle.position.z = 0.0;
  58905. particle.rotation.x = 0.0;
  58906. particle.rotation.y = 0.0;
  58907. particle.rotation.z = 0.0;
  58908. particle.rotationQuaternion = null;
  58909. particle.scaling.x = 1.0;
  58910. particle.scaling.y = 1.0;
  58911. particle.scaling.z = 1.0;
  58912. particle.uvs.x = 0.0;
  58913. particle.uvs.y = 0.0;
  58914. particle.uvs.z = 1.0;
  58915. particle.uvs.w = 1.0;
  58916. particle.pivot.x = 0.0;
  58917. particle.pivot.y = 0.0;
  58918. particle.pivot.z = 0.0;
  58919. particle.translateFromPivot = false;
  58920. particle.parentId = null;
  58921. };
  58922. /**
  58923. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58924. * @returns the SPS.
  58925. */
  58926. SolidParticleSystem.prototype.rebuildMesh = function () {
  58927. for (var p = 0; p < this.particles.length; p++) {
  58928. this._rebuildParticle(this.particles[p]);
  58929. }
  58930. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58931. return this;
  58932. };
  58933. /**
  58934. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58935. * This method calls `updateParticle()` for each particle of the SPS.
  58936. * For an animated SPS, it is usually called within the render loop.
  58937. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58938. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58939. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58940. * @returns the SPS.
  58941. */
  58942. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58943. if (start === void 0) { start = 0; }
  58944. if (end === void 0) { end = this.nbParticles - 1; }
  58945. if (update === void 0) { update = true; }
  58946. if (!this._updatable) {
  58947. return this;
  58948. }
  58949. // custom beforeUpdate
  58950. this.beforeUpdateParticles(start, end, update);
  58951. this._cam_axisX.x = 1.0;
  58952. this._cam_axisX.y = 0.0;
  58953. this._cam_axisX.z = 0.0;
  58954. this._cam_axisY.x = 0.0;
  58955. this._cam_axisY.y = 1.0;
  58956. this._cam_axisY.z = 0.0;
  58957. this._cam_axisZ.x = 0.0;
  58958. this._cam_axisZ.y = 0.0;
  58959. this._cam_axisZ.z = 1.0;
  58960. // cases when the World Matrix is to be computed first
  58961. if (this.billboard || this._depthSort) {
  58962. this.mesh.computeWorldMatrix(true);
  58963. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58964. }
  58965. // if the particles will always face the camera
  58966. if (this.billboard) {
  58967. // compute the camera position and un-rotate it by the current mesh rotation
  58968. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58969. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58970. this._cam_axisZ.normalize();
  58971. // same for camera up vector extracted from the cam view matrix
  58972. var view = this._camera.getViewMatrix(true);
  58973. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58974. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58975. this._cam_axisY.normalize();
  58976. this._cam_axisX.normalize();
  58977. }
  58978. // if depthSort, compute the camera global position in the mesh local system
  58979. if (this._depthSort) {
  58980. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58981. }
  58982. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58983. var idx = 0; // current position index in the global array positions32
  58984. var index = 0; // position start index in the global array positions32 of the current particle
  58985. var colidx = 0; // current color index in the global array colors32
  58986. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58987. var uvidx = 0; // current uv index in the global array uvs32
  58988. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58989. var pt = 0; // current index in the particle model shape
  58990. if (this.mesh.isFacetDataEnabled) {
  58991. this._computeBoundingBox = true;
  58992. }
  58993. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58994. if (this._computeBoundingBox) {
  58995. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58996. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58997. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58998. }
  58999. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59000. if (this.mesh._boundingInfo) {
  59001. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59002. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59003. }
  59004. }
  59005. }
  59006. // particle loop
  59007. index = this.particles[start]._pos;
  59008. var vpos = (index / 3) | 0;
  59009. colorIndex = vpos * 4;
  59010. uvIndex = vpos * 2;
  59011. for (var p = start; p <= end; p++) {
  59012. this._particle = this.particles[p];
  59013. this._shape = this._particle._model._shape;
  59014. this._shapeUV = this._particle._model._shapeUV;
  59015. // call to custom user function to update the particle properties
  59016. this.updateParticle(this._particle);
  59017. // camera-particle distance for depth sorting
  59018. if (this._depthSort && this._depthSortParticles) {
  59019. var dsp = this.depthSortedParticles[p];
  59020. dsp.ind = this._particle._ind;
  59021. dsp.indicesLength = this._particle._model._indicesLength;
  59022. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59023. }
  59024. // skip the computations for inactive or already invisible particles
  59025. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59026. // increment indexes for the next particle
  59027. pt = this._shape.length;
  59028. index += pt * 3;
  59029. colorIndex += pt * 4;
  59030. uvIndex += pt * 2;
  59031. continue;
  59032. }
  59033. if (this._particle.isVisible) {
  59034. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59035. this._particleHasParent = (this._particle.parentId !== null);
  59036. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59037. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59038. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59039. // particle rotation matrix
  59040. if (this.billboard) {
  59041. this._particle.rotation.x = 0.0;
  59042. this._particle.rotation.y = 0.0;
  59043. }
  59044. if (this._computeParticleRotation || this.billboard) {
  59045. if (this._particle.rotationQuaternion) {
  59046. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59047. }
  59048. else {
  59049. this._yaw = this._particle.rotation.y;
  59050. this._pitch = this._particle.rotation.x;
  59051. this._roll = this._particle.rotation.z;
  59052. this._quaternionRotationYPR();
  59053. }
  59054. this._quaternionToRotationMatrix();
  59055. }
  59056. if (this._particleHasParent) {
  59057. this._parent = this.particles[this._particle.parentId];
  59058. 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];
  59059. 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];
  59060. 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];
  59061. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59062. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59063. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59064. if (this._computeParticleRotation || this.billboard) {
  59065. 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];
  59066. 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];
  59067. 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];
  59068. 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];
  59069. 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];
  59070. 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];
  59071. 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];
  59072. 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];
  59073. 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];
  59074. }
  59075. }
  59076. else {
  59077. this._particle._globalPosition.x = this._particle.position.x;
  59078. this._particle._globalPosition.y = this._particle.position.y;
  59079. this._particle._globalPosition.z = this._particle.position.z;
  59080. if (this._computeParticleRotation || this.billboard) {
  59081. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59082. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59083. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59084. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59085. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59086. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59087. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59088. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59089. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59090. }
  59091. }
  59092. if (this._particle.translateFromPivot) {
  59093. this._pivotBackTranslation.x = 0.0;
  59094. this._pivotBackTranslation.y = 0.0;
  59095. this._pivotBackTranslation.z = 0.0;
  59096. }
  59097. else {
  59098. this._pivotBackTranslation.x = this._scaledPivot.x;
  59099. this._pivotBackTranslation.y = this._scaledPivot.y;
  59100. this._pivotBackTranslation.z = this._scaledPivot.z;
  59101. }
  59102. // particle vertex loop
  59103. for (pt = 0; pt < this._shape.length; pt++) {
  59104. idx = index + pt * 3;
  59105. colidx = colorIndex + pt * 4;
  59106. uvidx = uvIndex + pt * 2;
  59107. this._vertex.x = this._shape[pt].x;
  59108. this._vertex.y = this._shape[pt].y;
  59109. this._vertex.z = this._shape[pt].z;
  59110. if (this._computeParticleVertex) {
  59111. this.updateParticleVertex(this._particle, this._vertex, pt);
  59112. }
  59113. // positions
  59114. this._vertex.x *= this._particle.scaling.x;
  59115. this._vertex.y *= this._particle.scaling.y;
  59116. this._vertex.z *= this._particle.scaling.z;
  59117. this._vertex.x -= this._scaledPivot.x;
  59118. this._vertex.y -= this._scaledPivot.y;
  59119. this._vertex.z -= this._scaledPivot.z;
  59120. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59121. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59122. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59123. this._rotated.x += this._pivotBackTranslation.x;
  59124. this._rotated.y += this._pivotBackTranslation.y;
  59125. this._rotated.z += this._pivotBackTranslation.z;
  59126. 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;
  59127. 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;
  59128. 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;
  59129. if (this._computeBoundingBox) {
  59130. if (this._positions32[idx] < this._minimum.x) {
  59131. this._minimum.x = this._positions32[idx];
  59132. }
  59133. if (this._positions32[idx] > this._maximum.x) {
  59134. this._maximum.x = this._positions32[idx];
  59135. }
  59136. if (this._positions32[idx + 1] < this._minimum.y) {
  59137. this._minimum.y = this._positions32[idx + 1];
  59138. }
  59139. if (this._positions32[idx + 1] > this._maximum.y) {
  59140. this._maximum.y = this._positions32[idx + 1];
  59141. }
  59142. if (this._positions32[idx + 2] < this._minimum.z) {
  59143. this._minimum.z = this._positions32[idx + 2];
  59144. }
  59145. if (this._positions32[idx + 2] > this._maximum.z) {
  59146. this._maximum.z = this._positions32[idx + 2];
  59147. }
  59148. }
  59149. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59150. if (!this._computeParticleVertex) {
  59151. this._normal.x = this._fixedNormal32[idx];
  59152. this._normal.y = this._fixedNormal32[idx + 1];
  59153. this._normal.z = this._fixedNormal32[idx + 2];
  59154. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59155. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59156. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59157. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59158. 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;
  59159. 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;
  59160. }
  59161. if (this._computeParticleColor && this._particle.color) {
  59162. this._colors32[colidx] = this._particle.color.r;
  59163. this._colors32[colidx + 1] = this._particle.color.g;
  59164. this._colors32[colidx + 2] = this._particle.color.b;
  59165. this._colors32[colidx + 3] = this._particle.color.a;
  59166. }
  59167. if (this._computeParticleTexture) {
  59168. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59169. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59170. }
  59171. }
  59172. }
  59173. // particle just set invisible : scaled to zero and positioned at the origin
  59174. else {
  59175. this._particle._stillInvisible = true; // mark the particle as invisible
  59176. for (pt = 0; pt < this._shape.length; pt++) {
  59177. idx = index + pt * 3;
  59178. colidx = colorIndex + pt * 4;
  59179. uvidx = uvIndex + pt * 2;
  59180. this._positions32[idx] = 0.0;
  59181. this._positions32[idx + 1] = 0.0;
  59182. this._positions32[idx + 2] = 0.0;
  59183. this._normals32[idx] = 0.0;
  59184. this._normals32[idx + 1] = 0.0;
  59185. this._normals32[idx + 2] = 0.0;
  59186. if (this._computeParticleColor && this._particle.color) {
  59187. this._colors32[colidx] = this._particle.color.r;
  59188. this._colors32[colidx + 1] = this._particle.color.g;
  59189. this._colors32[colidx + 2] = this._particle.color.b;
  59190. this._colors32[colidx + 3] = this._particle.color.a;
  59191. }
  59192. if (this._computeParticleTexture) {
  59193. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59194. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59195. }
  59196. }
  59197. }
  59198. // if the particle intersections must be computed : update the bbInfo
  59199. if (this._particlesIntersect) {
  59200. var bInfo = this._particle._boundingInfo;
  59201. var bBox = bInfo.boundingBox;
  59202. var bSphere = bInfo.boundingSphere;
  59203. if (!this._bSphereOnly) {
  59204. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59205. for (var b = 0; b < bBox.vectors.length; b++) {
  59206. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59207. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59208. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59209. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59210. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59211. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59212. 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;
  59213. 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;
  59214. 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;
  59215. }
  59216. bBox._update(this.mesh._worldMatrix);
  59217. }
  59218. // place and scale the particle bouding sphere in the SPS local system, then update it
  59219. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59220. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59221. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59222. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59223. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59224. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59225. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59226. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59227. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59228. 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));
  59229. bSphere._update(this.mesh._worldMatrix);
  59230. }
  59231. // increment indexes for the next particle
  59232. index = idx + 3;
  59233. colorIndex = colidx + 4;
  59234. uvIndex = uvidx + 2;
  59235. }
  59236. // if the VBO must be updated
  59237. if (update) {
  59238. if (this._computeParticleColor) {
  59239. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59240. }
  59241. if (this._computeParticleTexture) {
  59242. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59243. }
  59244. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59245. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59246. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59247. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59248. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59249. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59250. for (var i = 0; i < this._normals32.length; i++) {
  59251. this._fixedNormal32[i] = this._normals32[i];
  59252. }
  59253. }
  59254. if (!this.mesh.areNormalsFrozen) {
  59255. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59256. }
  59257. }
  59258. if (this._depthSort && this._depthSortParticles) {
  59259. this.depthSortedParticles.sort(this._depthSortFunction);
  59260. var dspl = this.depthSortedParticles.length;
  59261. var sorted = 0;
  59262. var lind = 0;
  59263. var sind = 0;
  59264. var sid = 0;
  59265. for (sorted = 0; sorted < dspl; sorted++) {
  59266. lind = this.depthSortedParticles[sorted].indicesLength;
  59267. sind = this.depthSortedParticles[sorted].ind;
  59268. for (var i = 0; i < lind; i++) {
  59269. this._indices32[sid] = this._indices[sind + i];
  59270. sid++;
  59271. }
  59272. }
  59273. this.mesh.updateIndices(this._indices32);
  59274. }
  59275. }
  59276. if (this._computeBoundingBox) {
  59277. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59278. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59279. }
  59280. this.afterUpdateParticles(start, end, update);
  59281. return this;
  59282. };
  59283. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59284. this._halfroll = this._roll * 0.5;
  59285. this._halfpitch = this._pitch * 0.5;
  59286. this._halfyaw = this._yaw * 0.5;
  59287. this._sinRoll = Math.sin(this._halfroll);
  59288. this._cosRoll = Math.cos(this._halfroll);
  59289. this._sinPitch = Math.sin(this._halfpitch);
  59290. this._cosPitch = Math.cos(this._halfpitch);
  59291. this._sinYaw = Math.sin(this._halfyaw);
  59292. this._cosYaw = Math.cos(this._halfyaw);
  59293. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59294. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59295. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59296. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59297. };
  59298. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59299. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59300. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59301. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59302. this._rotMatrix.m[3] = 0;
  59303. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59304. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59305. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59306. this._rotMatrix.m[7] = 0;
  59307. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59308. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59309. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59310. this._rotMatrix.m[11] = 0;
  59311. this._rotMatrix.m[12] = 0;
  59312. this._rotMatrix.m[13] = 0;
  59313. this._rotMatrix.m[14] = 0;
  59314. this._rotMatrix.m[15] = 1.0;
  59315. };
  59316. /**
  59317. * Disposes the SPS.
  59318. */
  59319. SolidParticleSystem.prototype.dispose = function () {
  59320. this.mesh.dispose();
  59321. this.vars = null;
  59322. // drop references to internal big arrays for the GC
  59323. this._positions = null;
  59324. this._indices = null;
  59325. this._normals = null;
  59326. this._uvs = null;
  59327. this._colors = null;
  59328. this._indices32 = null;
  59329. this._positions32 = null;
  59330. this._normals32 = null;
  59331. this._fixedNormal32 = null;
  59332. this._uvs32 = null;
  59333. this._colors32 = null;
  59334. this.pickedParticles = null;
  59335. };
  59336. /**
  59337. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59338. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59339. * @returns the SPS.
  59340. */
  59341. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59342. if (!this._isVisibilityBoxLocked) {
  59343. this.mesh.refreshBoundingInfo();
  59344. }
  59345. return this;
  59346. };
  59347. /**
  59348. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59349. * @param size the size (float) of the visibility box
  59350. * note : this doesn't lock the SPS mesh bounding box.
  59351. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59352. */
  59353. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59354. var vis = size / 2;
  59355. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59356. };
  59357. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59358. /**
  59359. * Gets whether the SPS as always visible or not
  59360. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59361. */
  59362. get: function () {
  59363. return this._alwaysVisible;
  59364. },
  59365. /**
  59366. * Sets the SPS as always visible or not
  59367. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59368. */
  59369. set: function (val) {
  59370. this._alwaysVisible = val;
  59371. this.mesh.alwaysSelectAsActiveMesh = val;
  59372. },
  59373. enumerable: true,
  59374. configurable: true
  59375. });
  59376. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59377. /**
  59378. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59379. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59380. */
  59381. get: function () {
  59382. return this._isVisibilityBoxLocked;
  59383. },
  59384. /**
  59385. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59386. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59387. */
  59388. set: function (val) {
  59389. this._isVisibilityBoxLocked = val;
  59390. var boundingInfo = this.mesh.getBoundingInfo();
  59391. boundingInfo.isLocked = val;
  59392. },
  59393. enumerable: true,
  59394. configurable: true
  59395. });
  59396. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59397. /**
  59398. * Gets if `setParticles()` computes the particle rotations or not.
  59399. * Default value : true. The SPS is faster when it's set to false.
  59400. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59401. */
  59402. get: function () {
  59403. return this._computeParticleRotation;
  59404. },
  59405. /**
  59406. * Tells to `setParticles()` to compute the particle rotations or not.
  59407. * Default value : true. The SPS is faster when it's set to false.
  59408. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59409. */
  59410. set: function (val) {
  59411. this._computeParticleRotation = val;
  59412. },
  59413. enumerable: true,
  59414. configurable: true
  59415. });
  59416. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59417. /**
  59418. * Gets if `setParticles()` computes the particle colors or not.
  59419. * Default value : true. The SPS is faster when it's set to false.
  59420. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59421. */
  59422. get: function () {
  59423. return this._computeParticleColor;
  59424. },
  59425. /**
  59426. * Tells to `setParticles()` to compute the particle colors or not.
  59427. * Default value : true. The SPS is faster when it's set to false.
  59428. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59429. */
  59430. set: function (val) {
  59431. this._computeParticleColor = val;
  59432. },
  59433. enumerable: true,
  59434. configurable: true
  59435. });
  59436. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59437. /**
  59438. * Gets if `setParticles()` computes the particle textures or not.
  59439. * Default value : true. The SPS is faster when it's set to false.
  59440. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59441. */
  59442. get: function () {
  59443. return this._computeParticleTexture;
  59444. },
  59445. set: function (val) {
  59446. this._computeParticleTexture = val;
  59447. },
  59448. enumerable: true,
  59449. configurable: true
  59450. });
  59451. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59452. /**
  59453. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59454. * Default value : false. The SPS is faster when it's set to false.
  59455. * Note : the particle custom vertex positions aren't stored values.
  59456. */
  59457. get: function () {
  59458. return this._computeParticleVertex;
  59459. },
  59460. /**
  59461. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59462. * Default value : false. The SPS is faster when it's set to false.
  59463. * Note : the particle custom vertex positions aren't stored values.
  59464. */
  59465. set: function (val) {
  59466. this._computeParticleVertex = val;
  59467. },
  59468. enumerable: true,
  59469. configurable: true
  59470. });
  59471. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59472. /**
  59473. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59474. */
  59475. get: function () {
  59476. return this._computeBoundingBox;
  59477. },
  59478. /**
  59479. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59480. */
  59481. set: function (val) {
  59482. this._computeBoundingBox = val;
  59483. },
  59484. enumerable: true,
  59485. configurable: true
  59486. });
  59487. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59488. /**
  59489. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59490. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59491. * Default : `true`
  59492. */
  59493. get: function () {
  59494. return this._depthSortParticles;
  59495. },
  59496. /**
  59497. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59498. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59499. * Default : `true`
  59500. */
  59501. set: function (val) {
  59502. this._depthSortParticles = val;
  59503. },
  59504. enumerable: true,
  59505. configurable: true
  59506. });
  59507. // =======================================================================
  59508. // Particle behavior logic
  59509. // these following methods may be overwritten by the user to fit his needs
  59510. /**
  59511. * This function does nothing. It may be overwritten to set all the particle first values.
  59512. * The SPS doesn't call this function, you may have to call it by your own.
  59513. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59514. */
  59515. SolidParticleSystem.prototype.initParticles = function () {
  59516. };
  59517. /**
  59518. * This function does nothing. It may be overwritten to recycle a particle.
  59519. * The SPS doesn't call this function, you may have to call it by your own.
  59520. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59521. * @param particle The particle to recycle
  59522. * @returns the recycled particle
  59523. */
  59524. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59525. return particle;
  59526. };
  59527. /**
  59528. * Updates a particle : this function should be overwritten by the user.
  59529. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59530. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59531. * @example : just set a particle position or velocity and recycle conditions
  59532. * @param particle The particle to update
  59533. * @returns the updated particle
  59534. */
  59535. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59536. return particle;
  59537. };
  59538. /**
  59539. * Updates a vertex of a particle : it can be overwritten by the user.
  59540. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59541. * @param particle the current particle
  59542. * @param vertex the current index of the current particle
  59543. * @param pt the index of the current vertex in the particle shape
  59544. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59545. * @example : just set a vertex particle position
  59546. * @returns the updated vertex
  59547. */
  59548. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59549. return vertex;
  59550. };
  59551. /**
  59552. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59553. * This does nothing and may be overwritten by the user.
  59554. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59555. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59556. * @param update the boolean update value actually passed to setParticles()
  59557. */
  59558. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59559. };
  59560. /**
  59561. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59562. * This will be passed three parameters.
  59563. * This does nothing and may be overwritten by the user.
  59564. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59565. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59566. * @param update the boolean update value actually passed to setParticles()
  59567. */
  59568. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59569. };
  59570. return SolidParticleSystem;
  59571. }());
  59572. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59573. })(BABYLON || (BABYLON = {}));
  59574. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59575. var BABYLON;
  59576. (function (BABYLON) {
  59577. var ShaderMaterial = /** @class */ (function (_super) {
  59578. __extends(ShaderMaterial, _super);
  59579. function ShaderMaterial(name, scene, shaderPath, options) {
  59580. var _this = _super.call(this, name, scene) || this;
  59581. _this._textures = {};
  59582. _this._textureArrays = {};
  59583. _this._floats = {};
  59584. _this._ints = {};
  59585. _this._floatsArrays = {};
  59586. _this._colors3 = {};
  59587. _this._colors3Arrays = {};
  59588. _this._colors4 = {};
  59589. _this._vectors2 = {};
  59590. _this._vectors3 = {};
  59591. _this._vectors4 = {};
  59592. _this._matrices = {};
  59593. _this._matrices3x3 = {};
  59594. _this._matrices2x2 = {};
  59595. _this._vectors2Arrays = {};
  59596. _this._vectors3Arrays = {};
  59597. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59598. _this._shaderPath = shaderPath;
  59599. options.needAlphaBlending = options.needAlphaBlending || false;
  59600. options.needAlphaTesting = options.needAlphaTesting || false;
  59601. options.attributes = options.attributes || ["position", "normal", "uv"];
  59602. options.uniforms = options.uniforms || ["worldViewProjection"];
  59603. options.uniformBuffers = options.uniformBuffers || [];
  59604. options.samplers = options.samplers || [];
  59605. options.defines = options.defines || [];
  59606. _this._options = options;
  59607. return _this;
  59608. }
  59609. ShaderMaterial.prototype.getClassName = function () {
  59610. return "ShaderMaterial";
  59611. };
  59612. ShaderMaterial.prototype.needAlphaBlending = function () {
  59613. return this._options.needAlphaBlending;
  59614. };
  59615. ShaderMaterial.prototype.needAlphaTesting = function () {
  59616. return this._options.needAlphaTesting;
  59617. };
  59618. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59619. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59620. this._options.uniforms.push(uniformName);
  59621. }
  59622. };
  59623. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59624. if (this._options.samplers.indexOf(name) === -1) {
  59625. this._options.samplers.push(name);
  59626. }
  59627. this._textures[name] = texture;
  59628. return this;
  59629. };
  59630. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59631. if (this._options.samplers.indexOf(name) === -1) {
  59632. this._options.samplers.push(name);
  59633. }
  59634. this._checkUniform(name);
  59635. this._textureArrays[name] = textures;
  59636. return this;
  59637. };
  59638. ShaderMaterial.prototype.setFloat = function (name, value) {
  59639. this._checkUniform(name);
  59640. this._floats[name] = value;
  59641. return this;
  59642. };
  59643. ShaderMaterial.prototype.setInt = function (name, value) {
  59644. this._checkUniform(name);
  59645. this._ints[name] = value;
  59646. return this;
  59647. };
  59648. ShaderMaterial.prototype.setFloats = function (name, value) {
  59649. this._checkUniform(name);
  59650. this._floatsArrays[name] = value;
  59651. return this;
  59652. };
  59653. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59654. this._checkUniform(name);
  59655. this._colors3[name] = value;
  59656. return this;
  59657. };
  59658. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59659. this._checkUniform(name);
  59660. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59661. color.toArray(arr, arr.length);
  59662. return arr;
  59663. }, []);
  59664. return this;
  59665. };
  59666. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59667. this._checkUniform(name);
  59668. this._colors4[name] = value;
  59669. return this;
  59670. };
  59671. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59672. this._checkUniform(name);
  59673. this._vectors2[name] = value;
  59674. return this;
  59675. };
  59676. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59677. this._checkUniform(name);
  59678. this._vectors3[name] = value;
  59679. return this;
  59680. };
  59681. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59682. this._checkUniform(name);
  59683. this._vectors4[name] = value;
  59684. return this;
  59685. };
  59686. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59687. this._checkUniform(name);
  59688. this._matrices[name] = value;
  59689. return this;
  59690. };
  59691. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59692. this._checkUniform(name);
  59693. this._matrices3x3[name] = value;
  59694. return this;
  59695. };
  59696. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59697. this._checkUniform(name);
  59698. this._matrices2x2[name] = value;
  59699. return this;
  59700. };
  59701. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59702. this._checkUniform(name);
  59703. this._vectors2Arrays[name] = value;
  59704. return this;
  59705. };
  59706. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59707. this._checkUniform(name);
  59708. this._vectors3Arrays[name] = value;
  59709. return this;
  59710. };
  59711. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59712. if (!mesh) {
  59713. return true;
  59714. }
  59715. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59716. return false;
  59717. }
  59718. return false;
  59719. };
  59720. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59721. var scene = this.getScene();
  59722. var engine = scene.getEngine();
  59723. if (!this.checkReadyOnEveryCall) {
  59724. if (this._renderId === scene.getRenderId()) {
  59725. if (this._checkCache(scene, mesh, useInstances)) {
  59726. return true;
  59727. }
  59728. }
  59729. }
  59730. // Instances
  59731. var defines = [];
  59732. var attribs = [];
  59733. var fallbacks = new BABYLON.EffectFallbacks();
  59734. if (useInstances) {
  59735. defines.push("#define INSTANCES");
  59736. }
  59737. for (var index = 0; index < this._options.defines.length; index++) {
  59738. defines.push(this._options.defines[index]);
  59739. }
  59740. for (var index = 0; index < this._options.attributes.length; index++) {
  59741. attribs.push(this._options.attributes[index]);
  59742. }
  59743. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59744. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59745. defines.push("#define VERTEXCOLOR");
  59746. }
  59747. // Bones
  59748. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59749. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59750. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59751. if (mesh.numBoneInfluencers > 4) {
  59752. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59753. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59754. }
  59755. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59756. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59757. fallbacks.addCPUSkinningFallback(0, mesh);
  59758. if (this._options.uniforms.indexOf("mBones") === -1) {
  59759. this._options.uniforms.push("mBones");
  59760. }
  59761. }
  59762. else {
  59763. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59764. }
  59765. // Textures
  59766. for (var name in this._textures) {
  59767. if (!this._textures[name].isReady()) {
  59768. return false;
  59769. }
  59770. }
  59771. // Alpha test
  59772. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59773. defines.push("#define ALPHATEST");
  59774. }
  59775. var previousEffect = this._effect;
  59776. var join = defines.join("\n");
  59777. this._effect = engine.createEffect(this._shaderPath, {
  59778. attributes: attribs,
  59779. uniformsNames: this._options.uniforms,
  59780. uniformBuffersNames: this._options.uniformBuffers,
  59781. samplers: this._options.samplers,
  59782. defines: join,
  59783. fallbacks: fallbacks,
  59784. onCompiled: this.onCompiled,
  59785. onError: this.onError
  59786. }, engine);
  59787. if (!this._effect.isReady()) {
  59788. return false;
  59789. }
  59790. if (previousEffect !== this._effect) {
  59791. scene.resetCachedMaterial();
  59792. }
  59793. this._renderId = scene.getRenderId();
  59794. return true;
  59795. };
  59796. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59797. var scene = this.getScene();
  59798. if (!this._effect) {
  59799. return;
  59800. }
  59801. if (this._options.uniforms.indexOf("world") !== -1) {
  59802. this._effect.setMatrix("world", world);
  59803. }
  59804. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59805. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59806. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59807. }
  59808. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59809. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59810. }
  59811. };
  59812. ShaderMaterial.prototype.bind = function (world, mesh) {
  59813. // Std values
  59814. this.bindOnlyWorldMatrix(world);
  59815. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59816. if (this._options.uniforms.indexOf("view") !== -1) {
  59817. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59818. }
  59819. if (this._options.uniforms.indexOf("projection") !== -1) {
  59820. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59821. }
  59822. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59823. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59824. }
  59825. // Bones
  59826. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59827. var name;
  59828. // Texture
  59829. for (name in this._textures) {
  59830. this._effect.setTexture(name, this._textures[name]);
  59831. }
  59832. // Texture arrays
  59833. for (name in this._textureArrays) {
  59834. this._effect.setTextureArray(name, this._textureArrays[name]);
  59835. }
  59836. // Int
  59837. for (name in this._ints) {
  59838. this._effect.setInt(name, this._ints[name]);
  59839. }
  59840. // Float
  59841. for (name in this._floats) {
  59842. this._effect.setFloat(name, this._floats[name]);
  59843. }
  59844. // Floats
  59845. for (name in this._floatsArrays) {
  59846. this._effect.setArray(name, this._floatsArrays[name]);
  59847. }
  59848. // Color3
  59849. for (name in this._colors3) {
  59850. this._effect.setColor3(name, this._colors3[name]);
  59851. }
  59852. for (name in this._colors3Arrays) {
  59853. this._effect.setArray3(name, this._colors3Arrays[name]);
  59854. }
  59855. // Color4
  59856. for (name in this._colors4) {
  59857. var color = this._colors4[name];
  59858. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59859. }
  59860. // Vector2
  59861. for (name in this._vectors2) {
  59862. this._effect.setVector2(name, this._vectors2[name]);
  59863. }
  59864. // Vector3
  59865. for (name in this._vectors3) {
  59866. this._effect.setVector3(name, this._vectors3[name]);
  59867. }
  59868. // Vector4
  59869. for (name in this._vectors4) {
  59870. this._effect.setVector4(name, this._vectors4[name]);
  59871. }
  59872. // Matrix
  59873. for (name in this._matrices) {
  59874. this._effect.setMatrix(name, this._matrices[name]);
  59875. }
  59876. // Matrix 3x3
  59877. for (name in this._matrices3x3) {
  59878. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59879. }
  59880. // Matrix 2x2
  59881. for (name in this._matrices2x2) {
  59882. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59883. }
  59884. // Vector2Array
  59885. for (name in this._vectors2Arrays) {
  59886. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59887. }
  59888. // Vector3Array
  59889. for (name in this._vectors3Arrays) {
  59890. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59891. }
  59892. }
  59893. this._afterBind(mesh);
  59894. };
  59895. ShaderMaterial.prototype.getActiveTextures = function () {
  59896. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59897. for (var name in this._textures) {
  59898. activeTextures.push(this._textures[name]);
  59899. }
  59900. for (var name in this._textureArrays) {
  59901. var array = this._textureArrays[name];
  59902. for (var index = 0; index < array.length; index++) {
  59903. activeTextures.push(array[index]);
  59904. }
  59905. }
  59906. return activeTextures;
  59907. };
  59908. ShaderMaterial.prototype.hasTexture = function (texture) {
  59909. if (_super.prototype.hasTexture.call(this, texture)) {
  59910. return true;
  59911. }
  59912. for (var name in this._textures) {
  59913. if (this._textures[name] === texture) {
  59914. return true;
  59915. }
  59916. }
  59917. for (var name in this._textureArrays) {
  59918. var array = this._textureArrays[name];
  59919. for (var index = 0; index < array.length; index++) {
  59920. if (array[index] === texture) {
  59921. return true;
  59922. }
  59923. }
  59924. }
  59925. return false;
  59926. };
  59927. ShaderMaterial.prototype.clone = function (name) {
  59928. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59929. return newShaderMaterial;
  59930. };
  59931. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59932. if (forceDisposeTextures) {
  59933. var name;
  59934. for (name in this._textures) {
  59935. this._textures[name].dispose();
  59936. }
  59937. for (name in this._textureArrays) {
  59938. var array = this._textureArrays[name];
  59939. for (var index = 0; index < array.length; index++) {
  59940. array[index].dispose();
  59941. }
  59942. }
  59943. }
  59944. this._textures = {};
  59945. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59946. };
  59947. ShaderMaterial.prototype.serialize = function () {
  59948. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59949. serializationObject.customType = "BABYLON.ShaderMaterial";
  59950. serializationObject.options = this._options;
  59951. serializationObject.shaderPath = this._shaderPath;
  59952. var name;
  59953. // Texture
  59954. serializationObject.textures = {};
  59955. for (name in this._textures) {
  59956. serializationObject.textures[name] = this._textures[name].serialize();
  59957. }
  59958. // Texture arrays
  59959. serializationObject.textureArrays = {};
  59960. for (name in this._textureArrays) {
  59961. serializationObject.textureArrays[name] = [];
  59962. var array = this._textureArrays[name];
  59963. for (var index = 0; index < array.length; index++) {
  59964. serializationObject.textureArrays[name].push(array[index].serialize());
  59965. }
  59966. }
  59967. // Float
  59968. serializationObject.floats = {};
  59969. for (name in this._floats) {
  59970. serializationObject.floats[name] = this._floats[name];
  59971. }
  59972. // Float s
  59973. serializationObject.FloatArrays = {};
  59974. for (name in this._floatsArrays) {
  59975. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59976. }
  59977. // Color3
  59978. serializationObject.colors3 = {};
  59979. for (name in this._colors3) {
  59980. serializationObject.colors3[name] = this._colors3[name].asArray();
  59981. }
  59982. // Color3 array
  59983. serializationObject.colors3Arrays = {};
  59984. for (name in this._colors3Arrays) {
  59985. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59986. }
  59987. // Color4
  59988. serializationObject.colors4 = {};
  59989. for (name in this._colors4) {
  59990. serializationObject.colors4[name] = this._colors4[name].asArray();
  59991. }
  59992. // Vector2
  59993. serializationObject.vectors2 = {};
  59994. for (name in this._vectors2) {
  59995. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59996. }
  59997. // Vector3
  59998. serializationObject.vectors3 = {};
  59999. for (name in this._vectors3) {
  60000. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60001. }
  60002. // Vector4
  60003. serializationObject.vectors4 = {};
  60004. for (name in this._vectors4) {
  60005. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60006. }
  60007. // Matrix
  60008. serializationObject.matrices = {};
  60009. for (name in this._matrices) {
  60010. serializationObject.matrices[name] = this._matrices[name].asArray();
  60011. }
  60012. // Matrix 3x3
  60013. serializationObject.matrices3x3 = {};
  60014. for (name in this._matrices3x3) {
  60015. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60016. }
  60017. // Matrix 2x2
  60018. serializationObject.matrices2x2 = {};
  60019. for (name in this._matrices2x2) {
  60020. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60021. }
  60022. // Vector2Array
  60023. serializationObject.vectors2Arrays = {};
  60024. for (name in this._vectors2Arrays) {
  60025. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60026. }
  60027. // Vector3Array
  60028. serializationObject.vectors3Arrays = {};
  60029. for (name in this._vectors3Arrays) {
  60030. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60031. }
  60032. return serializationObject;
  60033. };
  60034. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60035. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60036. var name;
  60037. // Texture
  60038. for (name in source.textures) {
  60039. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60040. }
  60041. // Texture arrays
  60042. for (name in source.textureArrays) {
  60043. var array = source.textureArrays[name];
  60044. var textureArray = new Array();
  60045. for (var index = 0; index < array.length; index++) {
  60046. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60047. }
  60048. material.setTextureArray(name, textureArray);
  60049. }
  60050. // Float
  60051. for (name in source.floats) {
  60052. material.setFloat(name, source.floats[name]);
  60053. }
  60054. // Float s
  60055. for (name in source.floatsArrays) {
  60056. material.setFloats(name, source.floatsArrays[name]);
  60057. }
  60058. // Color3
  60059. for (name in source.colors3) {
  60060. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60061. }
  60062. // Color3 arrays
  60063. for (name in source.colors3Arrays) {
  60064. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60065. if (i % 3 === 0) {
  60066. arr.push([num]);
  60067. }
  60068. else {
  60069. arr[arr.length - 1].push(num);
  60070. }
  60071. return arr;
  60072. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60073. material.setColor3Array(name, colors);
  60074. }
  60075. // Color4
  60076. for (name in source.colors4) {
  60077. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60078. }
  60079. // Vector2
  60080. for (name in source.vectors2) {
  60081. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60082. }
  60083. // Vector3
  60084. for (name in source.vectors3) {
  60085. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60086. }
  60087. // Vector4
  60088. for (name in source.vectors4) {
  60089. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60090. }
  60091. // Matrix
  60092. for (name in source.matrices) {
  60093. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60094. }
  60095. // Matrix 3x3
  60096. for (name in source.matrices3x3) {
  60097. material.setMatrix3x3(name, source.matrices3x3[name]);
  60098. }
  60099. // Matrix 2x2
  60100. for (name in source.matrices2x2) {
  60101. material.setMatrix2x2(name, source.matrices2x2[name]);
  60102. }
  60103. // Vector2Array
  60104. for (name in source.vectors2Arrays) {
  60105. material.setArray2(name, source.vectors2Arrays[name]);
  60106. }
  60107. // Vector3Array
  60108. for (name in source.vectors3Arrays) {
  60109. material.setArray3(name, source.vectors3Arrays[name]);
  60110. }
  60111. return material;
  60112. };
  60113. return ShaderMaterial;
  60114. }(BABYLON.Material));
  60115. BABYLON.ShaderMaterial = ShaderMaterial;
  60116. })(BABYLON || (BABYLON = {}));
  60117. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60118. var BABYLON;
  60119. (function (BABYLON) {
  60120. var GroundMesh = /** @class */ (function (_super) {
  60121. __extends(GroundMesh, _super);
  60122. function GroundMesh(name, scene) {
  60123. var _this = _super.call(this, name, scene) || this;
  60124. _this.generateOctree = false;
  60125. return _this;
  60126. }
  60127. GroundMesh.prototype.getClassName = function () {
  60128. return "GroundMesh";
  60129. };
  60130. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60131. get: function () {
  60132. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60133. },
  60134. enumerable: true,
  60135. configurable: true
  60136. });
  60137. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60138. get: function () {
  60139. return this._subdivisionsX;
  60140. },
  60141. enumerable: true,
  60142. configurable: true
  60143. });
  60144. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60145. get: function () {
  60146. return this._subdivisionsY;
  60147. },
  60148. enumerable: true,
  60149. configurable: true
  60150. });
  60151. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60152. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60153. this._subdivisionsX = chunksCount;
  60154. this._subdivisionsY = chunksCount;
  60155. this.subdivide(chunksCount);
  60156. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60157. };
  60158. /**
  60159. * Returns a height (y) value in the Worl system :
  60160. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60161. * Returns the ground y position if (x, z) are outside the ground surface.
  60162. */
  60163. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60164. var world = this.getWorldMatrix();
  60165. var invMat = BABYLON.Tmp.Matrix[5];
  60166. world.invertToRef(invMat);
  60167. var tmpVect = BABYLON.Tmp.Vector3[8];
  60168. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60169. x = tmpVect.x;
  60170. z = tmpVect.z;
  60171. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60172. return this.position.y;
  60173. }
  60174. if (!this._heightQuads || this._heightQuads.length == 0) {
  60175. this._initHeightQuads();
  60176. this._computeHeightQuads();
  60177. }
  60178. var facet = this._getFacetAt(x, z);
  60179. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60180. // return y in the World system
  60181. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60182. return tmpVect.y;
  60183. };
  60184. /**
  60185. * Returns a normalized vector (Vector3) orthogonal to the ground
  60186. * at the ground coordinates (x, z) expressed in the World system.
  60187. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60188. */
  60189. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60190. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60191. this.getNormalAtCoordinatesToRef(x, z, normal);
  60192. return normal;
  60193. };
  60194. /**
  60195. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60196. * at the ground coordinates (x, z) expressed in the World system.
  60197. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60198. * Returns the GroundMesh.
  60199. */
  60200. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60201. var world = this.getWorldMatrix();
  60202. var tmpMat = BABYLON.Tmp.Matrix[5];
  60203. world.invertToRef(tmpMat);
  60204. var tmpVect = BABYLON.Tmp.Vector3[8];
  60205. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60206. x = tmpVect.x;
  60207. z = tmpVect.z;
  60208. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60209. return this;
  60210. }
  60211. if (!this._heightQuads || this._heightQuads.length == 0) {
  60212. this._initHeightQuads();
  60213. this._computeHeightQuads();
  60214. }
  60215. var facet = this._getFacetAt(x, z);
  60216. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60217. return this;
  60218. };
  60219. /**
  60220. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60221. * if the ground has been updated.
  60222. * This can be used in the render loop.
  60223. * Returns the GroundMesh.
  60224. */
  60225. GroundMesh.prototype.updateCoordinateHeights = function () {
  60226. if (!this._heightQuads || this._heightQuads.length == 0) {
  60227. this._initHeightQuads();
  60228. }
  60229. this._computeHeightQuads();
  60230. return this;
  60231. };
  60232. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60233. GroundMesh.prototype._getFacetAt = function (x, z) {
  60234. // retrieve col and row from x, z coordinates in the ground local system
  60235. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60236. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60237. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60238. var facet;
  60239. if (z < quad.slope.x * x + quad.slope.y) {
  60240. facet = quad.facet1;
  60241. }
  60242. else {
  60243. facet = quad.facet2;
  60244. }
  60245. return facet;
  60246. };
  60247. // Creates and populates the heightMap array with "facet" elements :
  60248. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60249. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60250. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60251. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60252. // Returns the GroundMesh.
  60253. GroundMesh.prototype._initHeightQuads = function () {
  60254. var subdivisionsX = this._subdivisionsX;
  60255. var subdivisionsY = this._subdivisionsY;
  60256. this._heightQuads = new Array();
  60257. for (var row = 0; row < subdivisionsY; row++) {
  60258. for (var col = 0; col < subdivisionsX; col++) {
  60259. 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) };
  60260. this._heightQuads[row * subdivisionsX + col] = quad;
  60261. }
  60262. }
  60263. return this;
  60264. };
  60265. // Compute each quad element values and update the the heightMap array :
  60266. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60267. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60268. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60269. // Returns the GroundMesh.
  60270. GroundMesh.prototype._computeHeightQuads = function () {
  60271. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60272. if (!positions) {
  60273. return this;
  60274. }
  60275. var v1 = BABYLON.Tmp.Vector3[3];
  60276. var v2 = BABYLON.Tmp.Vector3[2];
  60277. var v3 = BABYLON.Tmp.Vector3[1];
  60278. var v4 = BABYLON.Tmp.Vector3[0];
  60279. var v1v2 = BABYLON.Tmp.Vector3[4];
  60280. var v1v3 = BABYLON.Tmp.Vector3[5];
  60281. var v1v4 = BABYLON.Tmp.Vector3[6];
  60282. var norm1 = BABYLON.Tmp.Vector3[7];
  60283. var norm2 = BABYLON.Tmp.Vector3[8];
  60284. var i = 0;
  60285. var j = 0;
  60286. var k = 0;
  60287. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60288. var h = 0;
  60289. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60290. var d2 = 0;
  60291. var subdivisionsX = this._subdivisionsX;
  60292. var subdivisionsY = this._subdivisionsY;
  60293. for (var row = 0; row < subdivisionsY; row++) {
  60294. for (var col = 0; col < subdivisionsX; col++) {
  60295. i = col * 3;
  60296. j = row * (subdivisionsX + 1) * 3;
  60297. k = (row + 1) * (subdivisionsX + 1) * 3;
  60298. v1.x = positions[j + i];
  60299. v1.y = positions[j + i + 1];
  60300. v1.z = positions[j + i + 2];
  60301. v2.x = positions[j + i + 3];
  60302. v2.y = positions[j + i + 4];
  60303. v2.z = positions[j + i + 5];
  60304. v3.x = positions[k + i];
  60305. v3.y = positions[k + i + 1];
  60306. v3.z = positions[k + i + 2];
  60307. v4.x = positions[k + i + 3];
  60308. v4.y = positions[k + i + 4];
  60309. v4.z = positions[k + i + 5];
  60310. // 2D slope V1V4
  60311. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60312. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60313. // facet equations :
  60314. // we compute each facet normal vector
  60315. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60316. // we compute the value d by applying the equation to v1 which belongs to the plane
  60317. // then we store the facet equation in a Vector4
  60318. v2.subtractToRef(v1, v1v2);
  60319. v3.subtractToRef(v1, v1v3);
  60320. v4.subtractToRef(v1, v1v4);
  60321. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60322. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60323. norm1.normalize();
  60324. norm2.normalize();
  60325. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60326. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60327. var quad = this._heightQuads[row * subdivisionsX + col];
  60328. quad.slope.copyFromFloats(cd, h);
  60329. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60330. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60331. }
  60332. }
  60333. return this;
  60334. };
  60335. GroundMesh.prototype.serialize = function (serializationObject) {
  60336. _super.prototype.serialize.call(this, serializationObject);
  60337. serializationObject.subdivisionsX = this._subdivisionsX;
  60338. serializationObject.subdivisionsY = this._subdivisionsY;
  60339. serializationObject.minX = this._minX;
  60340. serializationObject.maxX = this._maxX;
  60341. serializationObject.minZ = this._minZ;
  60342. serializationObject.maxZ = this._maxZ;
  60343. serializationObject.width = this._width;
  60344. serializationObject.height = this._height;
  60345. };
  60346. GroundMesh.Parse = function (parsedMesh, scene) {
  60347. var result = new GroundMesh(parsedMesh.name, scene);
  60348. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60349. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60350. result._minX = parsedMesh.minX;
  60351. result._maxX = parsedMesh.maxX;
  60352. result._minZ = parsedMesh.minZ;
  60353. result._maxZ = parsedMesh.maxZ;
  60354. result._width = parsedMesh.width;
  60355. result._height = parsedMesh.height;
  60356. return result;
  60357. };
  60358. return GroundMesh;
  60359. }(BABYLON.Mesh));
  60360. BABYLON.GroundMesh = GroundMesh;
  60361. })(BABYLON || (BABYLON = {}));
  60362. //# sourceMappingURL=babylon.groundMesh.js.map
  60363. var BABYLON;
  60364. (function (BABYLON) {
  60365. /**
  60366. * Creates an instance based on a source mesh.
  60367. */
  60368. var InstancedMesh = /** @class */ (function (_super) {
  60369. __extends(InstancedMesh, _super);
  60370. function InstancedMesh(name, source) {
  60371. var _this = _super.call(this, name, source.getScene()) || this;
  60372. source.instances.push(_this);
  60373. _this._sourceMesh = source;
  60374. _this.position.copyFrom(source.position);
  60375. _this.rotation.copyFrom(source.rotation);
  60376. _this.scaling.copyFrom(source.scaling);
  60377. if (source.rotationQuaternion) {
  60378. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60379. }
  60380. _this.infiniteDistance = source.infiniteDistance;
  60381. _this.setPivotMatrix(source.getPivotMatrix());
  60382. _this.refreshBoundingInfo();
  60383. _this._syncSubMeshes();
  60384. return _this;
  60385. }
  60386. /**
  60387. * Returns the string "InstancedMesh".
  60388. */
  60389. InstancedMesh.prototype.getClassName = function () {
  60390. return "InstancedMesh";
  60391. };
  60392. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60393. // Methods
  60394. get: function () {
  60395. return this._sourceMesh.receiveShadows;
  60396. },
  60397. enumerable: true,
  60398. configurable: true
  60399. });
  60400. Object.defineProperty(InstancedMesh.prototype, "material", {
  60401. get: function () {
  60402. return this._sourceMesh.material;
  60403. },
  60404. enumerable: true,
  60405. configurable: true
  60406. });
  60407. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60408. get: function () {
  60409. return this._sourceMesh.visibility;
  60410. },
  60411. enumerable: true,
  60412. configurable: true
  60413. });
  60414. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60415. get: function () {
  60416. return this._sourceMesh.skeleton;
  60417. },
  60418. enumerable: true,
  60419. configurable: true
  60420. });
  60421. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60422. get: function () {
  60423. return this._sourceMesh.renderingGroupId;
  60424. },
  60425. set: function (value) {
  60426. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60427. return;
  60428. }
  60429. //no-op with warning
  60430. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60431. },
  60432. enumerable: true,
  60433. configurable: true
  60434. });
  60435. /**
  60436. * Returns the total number of vertices (integer).
  60437. */
  60438. InstancedMesh.prototype.getTotalVertices = function () {
  60439. return this._sourceMesh.getTotalVertices();
  60440. };
  60441. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60442. get: function () {
  60443. return this._sourceMesh;
  60444. },
  60445. enumerable: true,
  60446. configurable: true
  60447. });
  60448. /**
  60449. * Is this node ready to be used/rendered
  60450. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60451. * @return {boolean} is it ready
  60452. */
  60453. InstancedMesh.prototype.isReady = function (completeCheck) {
  60454. if (completeCheck === void 0) { completeCheck = false; }
  60455. return this._sourceMesh.isReady(completeCheck, true);
  60456. };
  60457. /**
  60458. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60459. */
  60460. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60461. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60462. };
  60463. /**
  60464. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60465. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60466. * The `data` are either a numeric array either a Float32Array.
  60467. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60468. * 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).
  60469. * Note that a new underlying VertexBuffer object is created each call.
  60470. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60471. *
  60472. * Possible `kind` values :
  60473. * - BABYLON.VertexBuffer.PositionKind
  60474. * - BABYLON.VertexBuffer.UVKind
  60475. * - BABYLON.VertexBuffer.UV2Kind
  60476. * - BABYLON.VertexBuffer.UV3Kind
  60477. * - BABYLON.VertexBuffer.UV4Kind
  60478. * - BABYLON.VertexBuffer.UV5Kind
  60479. * - BABYLON.VertexBuffer.UV6Kind
  60480. * - BABYLON.VertexBuffer.ColorKind
  60481. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60482. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60483. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60484. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60485. *
  60486. * Returns the Mesh.
  60487. */
  60488. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60489. if (this.sourceMesh) {
  60490. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60491. }
  60492. return this.sourceMesh;
  60493. };
  60494. /**
  60495. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60496. * If the mesh has no geometry, it is simply returned as it is.
  60497. * The `data` are either a numeric array either a Float32Array.
  60498. * No new underlying VertexBuffer object is created.
  60499. * 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.
  60500. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60501. *
  60502. * Possible `kind` values :
  60503. * - BABYLON.VertexBuffer.PositionKind
  60504. * - BABYLON.VertexBuffer.UVKind
  60505. * - BABYLON.VertexBuffer.UV2Kind
  60506. * - BABYLON.VertexBuffer.UV3Kind
  60507. * - BABYLON.VertexBuffer.UV4Kind
  60508. * - BABYLON.VertexBuffer.UV5Kind
  60509. * - BABYLON.VertexBuffer.UV6Kind
  60510. * - BABYLON.VertexBuffer.ColorKind
  60511. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60512. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60513. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60514. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60515. *
  60516. * Returns the Mesh.
  60517. */
  60518. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60519. if (this.sourceMesh) {
  60520. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60521. }
  60522. return this.sourceMesh;
  60523. };
  60524. /**
  60525. * Sets the mesh indices.
  60526. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60527. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60528. * This method creates a new index buffer each call.
  60529. * Returns the Mesh.
  60530. */
  60531. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60532. if (totalVertices === void 0) { totalVertices = null; }
  60533. if (this.sourceMesh) {
  60534. this.sourceMesh.setIndices(indices, totalVertices);
  60535. }
  60536. return this.sourceMesh;
  60537. };
  60538. /**
  60539. * Boolean : True if the mesh owns the requested kind of data.
  60540. */
  60541. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60542. return this._sourceMesh.isVerticesDataPresent(kind);
  60543. };
  60544. /**
  60545. * Returns an array of indices (IndicesArray).
  60546. */
  60547. InstancedMesh.prototype.getIndices = function () {
  60548. return this._sourceMesh.getIndices();
  60549. };
  60550. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60551. get: function () {
  60552. return this._sourceMesh._positions;
  60553. },
  60554. enumerable: true,
  60555. configurable: true
  60556. });
  60557. /**
  60558. * Sets a new updated BoundingInfo to the mesh.
  60559. * Returns the mesh.
  60560. */
  60561. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60562. var meshBB = this._sourceMesh.getBoundingInfo();
  60563. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60564. this._updateBoundingInfo();
  60565. return this;
  60566. };
  60567. InstancedMesh.prototype._preActivate = function () {
  60568. if (this._currentLOD) {
  60569. this._currentLOD._preActivate();
  60570. }
  60571. return this;
  60572. };
  60573. InstancedMesh.prototype._activate = function (renderId) {
  60574. if (this._currentLOD) {
  60575. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60576. }
  60577. return this;
  60578. };
  60579. /**
  60580. * Returns the current associated LOD AbstractMesh.
  60581. */
  60582. InstancedMesh.prototype.getLOD = function (camera) {
  60583. if (!camera) {
  60584. return this;
  60585. }
  60586. var boundingInfo = this.getBoundingInfo();
  60587. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60588. if (this._currentLOD === this.sourceMesh) {
  60589. return this;
  60590. }
  60591. return this._currentLOD;
  60592. };
  60593. InstancedMesh.prototype._syncSubMeshes = function () {
  60594. this.releaseSubMeshes();
  60595. if (this._sourceMesh.subMeshes) {
  60596. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60597. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60598. }
  60599. }
  60600. return this;
  60601. };
  60602. InstancedMesh.prototype._generatePointsArray = function () {
  60603. return this._sourceMesh._generatePointsArray();
  60604. };
  60605. /**
  60606. * Creates a new InstancedMesh from the current mesh.
  60607. * - name (string) : the cloned mesh name
  60608. * - newParent (optional Node) : the optional Node to parent the clone to.
  60609. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60610. *
  60611. * Returns the clone.
  60612. */
  60613. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60614. var result = this._sourceMesh.createInstance(name);
  60615. // Deep copy
  60616. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60617. // Bounding info
  60618. this.refreshBoundingInfo();
  60619. // Parent
  60620. if (newParent) {
  60621. result.parent = newParent;
  60622. }
  60623. if (!doNotCloneChildren) {
  60624. // Children
  60625. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60626. var mesh = this.getScene().meshes[index];
  60627. if (mesh.parent === this) {
  60628. mesh.clone(mesh.name, result);
  60629. }
  60630. }
  60631. }
  60632. result.computeWorldMatrix(true);
  60633. return result;
  60634. };
  60635. /**
  60636. * Disposes the InstancedMesh.
  60637. * Returns nothing.
  60638. */
  60639. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60640. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60641. // Remove from mesh
  60642. var index = this._sourceMesh.instances.indexOf(this);
  60643. this._sourceMesh.instances.splice(index, 1);
  60644. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60645. };
  60646. return InstancedMesh;
  60647. }(BABYLON.AbstractMesh));
  60648. BABYLON.InstancedMesh = InstancedMesh;
  60649. })(BABYLON || (BABYLON = {}));
  60650. //# sourceMappingURL=babylon.instancedMesh.js.map
  60651. var BABYLON;
  60652. (function (BABYLON) {
  60653. var LinesMesh = /** @class */ (function (_super) {
  60654. __extends(LinesMesh, _super);
  60655. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60656. if (scene === void 0) { scene = null; }
  60657. if (parent === void 0) { parent = null; }
  60658. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60659. _this.useVertexColor = useVertexColor;
  60660. _this.useVertexAlpha = useVertexAlpha;
  60661. _this.color = new BABYLON.Color3(1, 1, 1);
  60662. _this.alpha = 1;
  60663. if (source) {
  60664. _this.color = source.color.clone();
  60665. _this.alpha = source.alpha;
  60666. _this.useVertexColor = source.useVertexColor;
  60667. _this.useVertexAlpha = source.useVertexAlpha;
  60668. }
  60669. _this._intersectionThreshold = 0.1;
  60670. var defines = [];
  60671. var options = {
  60672. attributes: [BABYLON.VertexBuffer.PositionKind],
  60673. uniforms: ["world", "viewProjection"],
  60674. needAlphaBlending: true,
  60675. defines: defines
  60676. };
  60677. if (useVertexAlpha === false) {
  60678. options.needAlphaBlending = false;
  60679. }
  60680. if (!useVertexColor) {
  60681. options.uniforms.push("color");
  60682. }
  60683. else {
  60684. options.defines.push("#define VERTEXCOLOR");
  60685. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60686. }
  60687. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60688. return _this;
  60689. }
  60690. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60691. /**
  60692. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60693. * This margin is expressed in world space coordinates, so its value may vary.
  60694. * Default value is 0.1
  60695. * @returns the intersection Threshold value.
  60696. */
  60697. get: function () {
  60698. return this._intersectionThreshold;
  60699. },
  60700. /**
  60701. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60702. * This margin is expressed in world space coordinates, so its value may vary.
  60703. * @param value the new threshold to apply
  60704. */
  60705. set: function (value) {
  60706. if (this._intersectionThreshold === value) {
  60707. return;
  60708. }
  60709. this._intersectionThreshold = value;
  60710. if (this.geometry) {
  60711. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60712. }
  60713. },
  60714. enumerable: true,
  60715. configurable: true
  60716. });
  60717. /**
  60718. * Returns the string "LineMesh"
  60719. */
  60720. LinesMesh.prototype.getClassName = function () {
  60721. return "LinesMesh";
  60722. };
  60723. Object.defineProperty(LinesMesh.prototype, "material", {
  60724. get: function () {
  60725. return this._colorShader;
  60726. },
  60727. set: function (value) {
  60728. // Do nothing
  60729. },
  60730. enumerable: true,
  60731. configurable: true
  60732. });
  60733. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60734. get: function () {
  60735. return false;
  60736. },
  60737. enumerable: true,
  60738. configurable: true
  60739. });
  60740. LinesMesh.prototype.createInstance = function (name) {
  60741. throw new Error("LinesMeshes do not support createInstance.");
  60742. };
  60743. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60744. if (!this._geometry) {
  60745. return this;
  60746. }
  60747. // VBOs
  60748. this._geometry._bind(this._colorShader.getEffect());
  60749. // Color
  60750. if (!this.useVertexColor) {
  60751. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60752. }
  60753. return this;
  60754. };
  60755. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60756. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60757. return this;
  60758. }
  60759. var engine = this.getScene().getEngine();
  60760. // Draw order
  60761. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60762. return this;
  60763. };
  60764. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60765. this._colorShader.dispose();
  60766. _super.prototype.dispose.call(this, doNotRecurse);
  60767. };
  60768. /**
  60769. * Returns a new LineMesh object cloned from the current one.
  60770. */
  60771. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60772. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60773. };
  60774. return LinesMesh;
  60775. }(BABYLON.Mesh));
  60776. BABYLON.LinesMesh = LinesMesh;
  60777. })(BABYLON || (BABYLON = {}));
  60778. //# sourceMappingURL=babylon.linesMesh.js.map
  60779. var BABYLON;
  60780. (function (BABYLON) {
  60781. /**
  60782. * Class containing static functions to help procedurally build meshes
  60783. */
  60784. var MeshBuilder = /** @class */ (function () {
  60785. function MeshBuilder() {
  60786. }
  60787. MeshBuilder.updateSideOrientation = function (orientation) {
  60788. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60789. return BABYLON.Mesh.DOUBLESIDE;
  60790. }
  60791. if (orientation === undefined || orientation === null) {
  60792. return BABYLON.Mesh.FRONTSIDE;
  60793. }
  60794. return orientation;
  60795. };
  60796. /**
  60797. * Creates a box mesh
  60798. * * The parameter `size` sets the size (float) of each box side (default 1)
  60799. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60800. * * 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)
  60801. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60802. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60803. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60804. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60805. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60806. * @param name defines the name of the mesh
  60807. * @param options defines the options used to create the mesh
  60808. * @param scene defines the hosting scene
  60809. * @returns the box mesh
  60810. */
  60811. MeshBuilder.CreateBox = function (name, options, scene) {
  60812. if (scene === void 0) { scene = null; }
  60813. var box = new BABYLON.Mesh(name, scene);
  60814. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60815. box._originalBuilderSideOrientation = options.sideOrientation;
  60816. var vertexData = BABYLON.VertexData.CreateBox(options);
  60817. vertexData.applyToMesh(box, options.updatable);
  60818. return box;
  60819. };
  60820. /**
  60821. * Creates a sphere mesh
  60822. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60823. * * 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`)
  60824. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60825. * * 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
  60826. * * 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)
  60827. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60828. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60829. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60830. * @param name defines the name of the mesh
  60831. * @param options defines the options used to create the mesh
  60832. * @param scene defines the hosting scene
  60833. * @returns the sphere mesh
  60834. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60835. */
  60836. MeshBuilder.CreateSphere = function (name, options, scene) {
  60837. var sphere = new BABYLON.Mesh(name, scene);
  60838. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60839. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60840. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60841. vertexData.applyToMesh(sphere, options.updatable);
  60842. return sphere;
  60843. };
  60844. /**
  60845. * Creates a plane polygonal mesh. By default, this is a disc
  60846. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60847. * * 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
  60848. * * 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
  60849. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60850. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60851. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60852. * @param name defines the name of the mesh
  60853. * @param options defines the options used to create the mesh
  60854. * @param scene defines the hosting scene
  60855. * @returns the plane polygonal mesh
  60856. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60857. */
  60858. MeshBuilder.CreateDisc = function (name, options, scene) {
  60859. if (scene === void 0) { scene = null; }
  60860. var disc = new BABYLON.Mesh(name, scene);
  60861. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60862. disc._originalBuilderSideOrientation = options.sideOrientation;
  60863. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60864. vertexData.applyToMesh(disc, options.updatable);
  60865. return disc;
  60866. };
  60867. /**
  60868. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60869. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60870. * * 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`)
  60871. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60872. * * 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
  60873. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60874. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60875. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60876. * @param name defines the name of the mesh
  60877. * @param options defines the options used to create the mesh
  60878. * @param scene defines the hosting scene
  60879. * @returns the icosahedron mesh
  60880. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60881. */
  60882. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60883. var sphere = new BABYLON.Mesh(name, scene);
  60884. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60885. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60886. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60887. vertexData.applyToMesh(sphere, options.updatable);
  60888. return sphere;
  60889. };
  60890. ;
  60891. /**
  60892. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60893. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60894. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60895. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60896. * * 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
  60897. * * 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
  60898. * * 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
  60899. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60900. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60901. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60902. * * 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
  60903. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60904. * * 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
  60905. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60906. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60907. * @param name defines the name of the mesh
  60908. * @param options defines the options used to create the mesh
  60909. * @param scene defines the hosting scene
  60910. * @returns the ribbon mesh
  60911. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60912. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60913. */
  60914. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60915. if (scene === void 0) { scene = null; }
  60916. var pathArray = options.pathArray;
  60917. var closeArray = options.closeArray;
  60918. var closePath = options.closePath;
  60919. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60920. var instance = options.instance;
  60921. var updatable = options.updatable;
  60922. if (instance) { // existing ribbon instance update
  60923. // positionFunction : ribbon case
  60924. // only pathArray and sideOrientation parameters are taken into account for positions update
  60925. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60926. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60927. var positionFunction = function (positions) {
  60928. var minlg = pathArray[0].length;
  60929. var i = 0;
  60930. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60931. for (var si = 1; si <= ns; si++) {
  60932. for (var p = 0; p < pathArray.length; p++) {
  60933. var path = pathArray[p];
  60934. var l = path.length;
  60935. minlg = (minlg < l) ? minlg : l;
  60936. var j = 0;
  60937. while (j < minlg) {
  60938. positions[i] = path[j].x;
  60939. positions[i + 1] = path[j].y;
  60940. positions[i + 2] = path[j].z;
  60941. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60942. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60943. }
  60944. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60945. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60946. }
  60947. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60948. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60949. }
  60950. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60951. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60952. }
  60953. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60954. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60955. }
  60956. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60957. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60958. }
  60959. j++;
  60960. i += 3;
  60961. }
  60962. if (instance._closePath) {
  60963. positions[i] = path[0].x;
  60964. positions[i + 1] = path[0].y;
  60965. positions[i + 2] = path[0].z;
  60966. i += 3;
  60967. }
  60968. }
  60969. }
  60970. };
  60971. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60972. positionFunction(positions);
  60973. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60974. instance._boundingInfo.update(instance._worldMatrix);
  60975. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60976. if (options.colors) {
  60977. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60978. for (var c = 0; c < options.colors.length; c++) {
  60979. colors[c * 4] = options.colors[c].r;
  60980. colors[c * 4 + 1] = options.colors[c].g;
  60981. colors[c * 4 + 2] = options.colors[c].b;
  60982. colors[c * 4 + 3] = options.colors[c].a;
  60983. }
  60984. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60985. }
  60986. if (options.uvs) {
  60987. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60988. for (var i = 0; i < options.uvs.length; i++) {
  60989. uvs[i * 2] = options.uvs[i].x;
  60990. uvs[i * 2 + 1] = options.uvs[i].y;
  60991. }
  60992. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60993. }
  60994. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60995. var indices = instance.getIndices();
  60996. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60997. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60998. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60999. if (instance._closePath) {
  61000. var indexFirst = 0;
  61001. var indexLast = 0;
  61002. for (var p = 0; p < pathArray.length; p++) {
  61003. indexFirst = instance._idx[p] * 3;
  61004. if (p + 1 < pathArray.length) {
  61005. indexLast = (instance._idx[p + 1] - 1) * 3;
  61006. }
  61007. else {
  61008. indexLast = normals.length - 3;
  61009. }
  61010. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61011. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61012. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61013. normals[indexLast] = normals[indexFirst];
  61014. normals[indexLast + 1] = normals[indexFirst + 1];
  61015. normals[indexLast + 2] = normals[indexFirst + 2];
  61016. }
  61017. }
  61018. if (!(instance.areNormalsFrozen)) {
  61019. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61020. }
  61021. }
  61022. return instance;
  61023. }
  61024. else { // new ribbon creation
  61025. var ribbon = new BABYLON.Mesh(name, scene);
  61026. ribbon._originalBuilderSideOrientation = sideOrientation;
  61027. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61028. if (closePath) {
  61029. ribbon._idx = vertexData._idx;
  61030. }
  61031. ribbon._closePath = closePath;
  61032. ribbon._closeArray = closeArray;
  61033. vertexData.applyToMesh(ribbon, updatable);
  61034. return ribbon;
  61035. }
  61036. };
  61037. /**
  61038. * Creates a cylinder or a cone mesh
  61039. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61040. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61041. * * 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.
  61042. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61043. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61044. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61045. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61046. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61047. * * 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).
  61048. * * 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
  61049. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61050. * * 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
  61051. * * 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.
  61052. * * If `enclose` is false, a ring surface is one element.
  61053. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61054. * * 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
  61055. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61056. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61057. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61058. * @param name defines the name of the mesh
  61059. * @param options defines the options used to create the mesh
  61060. * @param scene defines the hosting scene
  61061. * @returns the cylinder mesh
  61062. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61063. */
  61064. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61065. var cylinder = new BABYLON.Mesh(name, scene);
  61066. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61067. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61068. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61069. vertexData.applyToMesh(cylinder, options.updatable);
  61070. return cylinder;
  61071. };
  61072. /**
  61073. * Creates a torus mesh
  61074. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61075. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61076. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61077. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61078. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61079. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61080. * @param name defines the name of the mesh
  61081. * @param options defines the options used to create the mesh
  61082. * @param scene defines the hosting scene
  61083. * @returns the torus mesh
  61084. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61085. */
  61086. MeshBuilder.CreateTorus = function (name, options, scene) {
  61087. var torus = new BABYLON.Mesh(name, scene);
  61088. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61089. torus._originalBuilderSideOrientation = options.sideOrientation;
  61090. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61091. vertexData.applyToMesh(torus, options.updatable);
  61092. return torus;
  61093. };
  61094. /**
  61095. * Creates a torus knot mesh
  61096. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61097. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61098. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61099. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61100. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61101. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61102. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61103. * @param name defines the name of the mesh
  61104. * @param options defines the options used to create the mesh
  61105. * @param scene defines the hosting scene
  61106. * @returns the torus knot mesh
  61107. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61108. */
  61109. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61110. var torusKnot = new BABYLON.Mesh(name, scene);
  61111. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61112. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61113. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61114. vertexData.applyToMesh(torusKnot, options.updatable);
  61115. return torusKnot;
  61116. };
  61117. /**
  61118. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61119. * * 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
  61120. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61121. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61122. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61123. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61124. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61125. * * 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
  61126. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61127. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61128. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61129. * @param name defines the name of the new line system
  61130. * @param options defines the options used to create the line system
  61131. * @param scene defines the hosting scene
  61132. * @returns a new line system mesh
  61133. */
  61134. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61135. var instance = options.instance;
  61136. var lines = options.lines;
  61137. var colors = options.colors;
  61138. if (instance) { // lines update
  61139. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61140. var vertexColor;
  61141. var lineColors;
  61142. if (colors) {
  61143. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61144. }
  61145. var i = 0;
  61146. var c = 0;
  61147. for (var l = 0; l < lines.length; l++) {
  61148. var points = lines[l];
  61149. for (var p = 0; p < points.length; p++) {
  61150. positions[i] = points[p].x;
  61151. positions[i + 1] = points[p].y;
  61152. positions[i + 2] = points[p].z;
  61153. if (colors && vertexColor) {
  61154. lineColors = colors[l];
  61155. vertexColor[c] = lineColors[p].r;
  61156. vertexColor[c + 1] = lineColors[p].g;
  61157. vertexColor[c + 2] = lineColors[p].b;
  61158. vertexColor[c + 3] = lineColors[p].a;
  61159. c += 4;
  61160. }
  61161. i += 3;
  61162. }
  61163. }
  61164. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61165. if (colors && vertexColor) {
  61166. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61167. }
  61168. return instance;
  61169. }
  61170. // line system creation
  61171. var useVertexColor = (colors) ? true : false;
  61172. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61173. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61174. vertexData.applyToMesh(lineSystem, options.updatable);
  61175. return lineSystem;
  61176. };
  61177. /**
  61178. * Creates a line mesh
  61179. * 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
  61180. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61181. * * The parameter `points` is an array successive Vector3
  61182. * * 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
  61183. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61184. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61185. * * When updating an instance, remember that only point positions can change, not the number of points
  61186. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61187. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61188. * @param name defines the name of the new line system
  61189. * @param options defines the options used to create the line system
  61190. * @param scene defines the hosting scene
  61191. * @returns a new line mesh
  61192. */
  61193. MeshBuilder.CreateLines = function (name, options, scene) {
  61194. if (scene === void 0) { scene = null; }
  61195. var colors = (options.colors) ? [options.colors] : null;
  61196. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61197. return lines;
  61198. };
  61199. /**
  61200. * Creates a dashed line mesh
  61201. * * 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
  61202. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61203. * * The parameter `points` is an array successive Vector3
  61204. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61205. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61206. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61207. * * 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
  61208. * * When updating an instance, remember that only point positions can change, not the number of points
  61209. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61210. * @param name defines the name of the mesh
  61211. * @param options defines the options used to create the mesh
  61212. * @param scene defines the hosting scene
  61213. * @returns the dashed line mesh
  61214. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61215. */
  61216. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61217. if (scene === void 0) { scene = null; }
  61218. var points = options.points;
  61219. var instance = options.instance;
  61220. var gapSize = options.gapSize || 1;
  61221. var dashSize = options.dashSize || 3;
  61222. if (instance) { // dashed lines update
  61223. var positionFunction = function (positions) {
  61224. var curvect = BABYLON.Vector3.Zero();
  61225. var nbSeg = positions.length / 6;
  61226. var lg = 0;
  61227. var nb = 0;
  61228. var shft = 0;
  61229. var dashshft = 0;
  61230. var curshft = 0;
  61231. var p = 0;
  61232. var i = 0;
  61233. var j = 0;
  61234. for (i = 0; i < points.length - 1; i++) {
  61235. points[i + 1].subtractToRef(points[i], curvect);
  61236. lg += curvect.length();
  61237. }
  61238. shft = lg / nbSeg;
  61239. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61240. for (i = 0; i < points.length - 1; i++) {
  61241. points[i + 1].subtractToRef(points[i], curvect);
  61242. nb = Math.floor(curvect.length() / shft);
  61243. curvect.normalize();
  61244. j = 0;
  61245. while (j < nb && p < positions.length) {
  61246. curshft = shft * j;
  61247. positions[p] = points[i].x + curshft * curvect.x;
  61248. positions[p + 1] = points[i].y + curshft * curvect.y;
  61249. positions[p + 2] = points[i].z + curshft * curvect.z;
  61250. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61251. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61252. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61253. p += 6;
  61254. j++;
  61255. }
  61256. }
  61257. while (p < positions.length) {
  61258. positions[p] = points[i].x;
  61259. positions[p + 1] = points[i].y;
  61260. positions[p + 2] = points[i].z;
  61261. p += 3;
  61262. }
  61263. };
  61264. instance.updateMeshPositions(positionFunction, false);
  61265. return instance;
  61266. }
  61267. // dashed lines creation
  61268. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61269. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61270. vertexData.applyToMesh(dashedLines, options.updatable);
  61271. dashedLines.dashSize = dashSize;
  61272. dashedLines.gapSize = gapSize;
  61273. return dashedLines;
  61274. };
  61275. /**
  61276. * 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.
  61277. * * 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.
  61278. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61279. * * 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.
  61280. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61281. * * 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
  61282. * * 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
  61283. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61284. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61285. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61286. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61287. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61288. * @param name defines the name of the mesh
  61289. * @param options defines the options used to create the mesh
  61290. * @param scene defines the hosting scene
  61291. * @returns the extruded shape mesh
  61292. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61293. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61294. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61295. */
  61296. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61297. if (scene === void 0) { scene = null; }
  61298. var path = options.path;
  61299. var shape = options.shape;
  61300. var scale = options.scale || 1;
  61301. var rotation = options.rotation || 0;
  61302. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61303. var updatable = options.updatable;
  61304. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61305. var instance = options.instance || null;
  61306. var invertUV = options.invertUV || false;
  61307. 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);
  61308. };
  61309. /**
  61310. * Creates an custom extruded shape mesh.
  61311. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61312. * * 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.
  61313. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61314. * * 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
  61315. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61316. * * 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
  61317. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61318. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61319. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61320. * * 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
  61321. * * 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
  61322. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61323. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61324. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61325. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61326. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61327. * @param name defines the name of the mesh
  61328. * @param options defines the options used to create the mesh
  61329. * @param scene defines the hosting scene
  61330. * @returns the custom extruded shape mesh
  61331. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61332. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61333. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61334. */
  61335. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61336. var path = options.path;
  61337. var shape = options.shape;
  61338. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61339. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61340. var ribbonCloseArray = options.ribbonCloseArray || false;
  61341. var ribbonClosePath = options.ribbonClosePath || false;
  61342. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61343. var updatable = options.updatable;
  61344. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61345. var instance = options.instance;
  61346. var invertUV = options.invertUV || false;
  61347. 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);
  61348. };
  61349. /**
  61350. * Creates lathe mesh.
  61351. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61352. * * 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
  61353. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61354. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61355. * * 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
  61356. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61357. * * 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
  61358. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61359. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61360. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61361. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61362. * @param name defines the name of the mesh
  61363. * @param options defines the options used to create the mesh
  61364. * @param scene defines the hosting scene
  61365. * @returns the lathe mesh
  61366. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61367. */
  61368. MeshBuilder.CreateLathe = function (name, options, scene) {
  61369. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61370. var closed = (options.closed === undefined) ? true : options.closed;
  61371. var shape = options.shape;
  61372. var radius = options.radius || 1;
  61373. var tessellation = options.tessellation || 64;
  61374. var updatable = options.updatable;
  61375. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61376. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61377. var pi2 = Math.PI * 2;
  61378. var paths = new Array();
  61379. var invertUV = options.invertUV || false;
  61380. var i = 0;
  61381. var p = 0;
  61382. var step = pi2 / tessellation * arc;
  61383. var rotated;
  61384. var path = new Array();
  61385. for (i = 0; i <= tessellation; i++) {
  61386. var path = [];
  61387. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61388. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61389. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61390. }
  61391. for (p = 0; p < shape.length; p++) {
  61392. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61393. path.push(rotated);
  61394. }
  61395. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61396. 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));
  61397. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61398. }
  61399. paths.push(path);
  61400. }
  61401. // lathe ribbon
  61402. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61403. return lathe;
  61404. };
  61405. /**
  61406. * Creates a plane mesh
  61407. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61408. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61409. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61410. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61411. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61412. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61413. * @param name defines the name of the mesh
  61414. * @param options defines the options used to create the mesh
  61415. * @param scene defines the hosting scene
  61416. * @returns the plane mesh
  61417. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61418. */
  61419. MeshBuilder.CreatePlane = function (name, options, scene) {
  61420. var plane = new BABYLON.Mesh(name, scene);
  61421. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61422. plane._originalBuilderSideOrientation = options.sideOrientation;
  61423. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61424. vertexData.applyToMesh(plane, options.updatable);
  61425. if (options.sourcePlane) {
  61426. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61427. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61428. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61429. plane.rotate(vectorProduct, product);
  61430. }
  61431. return plane;
  61432. };
  61433. /**
  61434. * Creates a ground mesh
  61435. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61436. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61437. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61438. * @param name defines the name of the mesh
  61439. * @param options defines the options used to create the mesh
  61440. * @param scene defines the hosting scene
  61441. * @returns the ground mesh
  61442. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61443. */
  61444. MeshBuilder.CreateGround = function (name, options, scene) {
  61445. var ground = new BABYLON.GroundMesh(name, scene);
  61446. ground._setReady(false);
  61447. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61448. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61449. ground._width = options.width || 1;
  61450. ground._height = options.height || 1;
  61451. ground._maxX = ground._width / 2;
  61452. ground._maxZ = ground._height / 2;
  61453. ground._minX = -ground._maxX;
  61454. ground._minZ = -ground._maxZ;
  61455. var vertexData = BABYLON.VertexData.CreateGround(options);
  61456. vertexData.applyToMesh(ground, options.updatable);
  61457. ground._setReady(true);
  61458. return ground;
  61459. };
  61460. /**
  61461. * Creates a tiled ground mesh
  61462. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61463. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61464. * * 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
  61465. * * 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
  61466. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61467. * @param name defines the name of the mesh
  61468. * @param options defines the options used to create the mesh
  61469. * @param scene defines the hosting scene
  61470. * @returns the tiled ground mesh
  61471. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61472. */
  61473. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61474. var tiledGround = new BABYLON.Mesh(name, scene);
  61475. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61476. vertexData.applyToMesh(tiledGround, options.updatable);
  61477. return tiledGround;
  61478. };
  61479. /**
  61480. * Creates a ground mesh from a height map
  61481. * * The parameter `url` sets the URL of the height map image resource.
  61482. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61483. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61484. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61485. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61486. * * 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.
  61487. * * 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).
  61488. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61489. * @param name defines the name of the mesh
  61490. * @param url defines the url to the height map
  61491. * @param options defines the options used to create the mesh
  61492. * @param scene defines the hosting scene
  61493. * @returns the ground mesh
  61494. * @see http://doc.babylonjs.com/babylon101/height_map
  61495. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61496. */
  61497. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61498. var width = options.width || 10.0;
  61499. var height = options.height || 10.0;
  61500. var subdivisions = options.subdivisions || 1 | 0;
  61501. var minHeight = options.minHeight || 0.0;
  61502. var maxHeight = options.maxHeight || 1.0;
  61503. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61504. var updatable = options.updatable;
  61505. var onReady = options.onReady;
  61506. var ground = new BABYLON.GroundMesh(name, scene);
  61507. ground._subdivisionsX = subdivisions;
  61508. ground._subdivisionsY = subdivisions;
  61509. ground._width = width;
  61510. ground._height = height;
  61511. ground._maxX = ground._width / 2.0;
  61512. ground._maxZ = ground._height / 2.0;
  61513. ground._minX = -ground._maxX;
  61514. ground._minZ = -ground._maxZ;
  61515. ground._setReady(false);
  61516. var onload = function (img) {
  61517. // Getting height map data
  61518. var canvas = document.createElement("canvas");
  61519. var context = canvas.getContext("2d");
  61520. if (!context) {
  61521. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61522. }
  61523. if (scene.isDisposed) {
  61524. return;
  61525. }
  61526. var bufferWidth = img.width;
  61527. var bufferHeight = img.height;
  61528. canvas.width = bufferWidth;
  61529. canvas.height = bufferHeight;
  61530. context.drawImage(img, 0, 0);
  61531. // Create VertexData from map data
  61532. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61533. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61534. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61535. width: width, height: height,
  61536. subdivisions: subdivisions,
  61537. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61538. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61539. });
  61540. vertexData.applyToMesh(ground, updatable);
  61541. //execute ready callback, if set
  61542. if (onReady) {
  61543. onReady(ground);
  61544. }
  61545. ground._setReady(true);
  61546. };
  61547. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61548. return ground;
  61549. };
  61550. /**
  61551. * Creates a polygon mesh
  61552. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61553. * * 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
  61554. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61555. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61556. * * 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)
  61557. * * Remember you can only change the shape positions, not their number when updating a polygon
  61558. * @param name defines the name of the mesh
  61559. * @param options defines the options used to create the mesh
  61560. * @param scene defines the hosting scene
  61561. * @returns the polygon mesh
  61562. */
  61563. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61564. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61565. var shape = options.shape;
  61566. var holes = options.holes || [];
  61567. var depth = options.depth || 0;
  61568. var contours = [];
  61569. var hole = [];
  61570. for (var i = 0; i < shape.length; i++) {
  61571. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61572. }
  61573. var epsilon = 0.00000001;
  61574. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61575. contours.pop();
  61576. }
  61577. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61578. for (var hNb = 0; hNb < holes.length; hNb++) {
  61579. hole = [];
  61580. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61581. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61582. }
  61583. polygonTriangulation.addHole(hole);
  61584. }
  61585. var polygon = polygonTriangulation.build(options.updatable, depth);
  61586. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61587. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61588. vertexData.applyToMesh(polygon, options.updatable);
  61589. return polygon;
  61590. };
  61591. ;
  61592. /**
  61593. * Creates an extruded polygon mesh, with depth in the Y direction.
  61594. * * 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)
  61595. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61596. * @param name defines the name of the mesh
  61597. * @param options defines the options used to create the mesh
  61598. * @param scene defines the hosting scene
  61599. * @returns the polygon mesh
  61600. */
  61601. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61602. return MeshBuilder.CreatePolygon(name, options, scene);
  61603. };
  61604. ;
  61605. /**
  61606. * Creates a tube mesh.
  61607. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61608. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61609. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61610. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61611. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61612. * * 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)
  61613. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61614. * * 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
  61615. * * 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
  61616. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61617. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61618. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61619. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61620. * @param name defines the name of the mesh
  61621. * @param options defines the options used to create the mesh
  61622. * @param scene defines the hosting scene
  61623. * @returns the tube mesh
  61624. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61625. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61626. */
  61627. MeshBuilder.CreateTube = function (name, options, scene) {
  61628. var path = options.path;
  61629. var instance = options.instance;
  61630. var radius = 1.0;
  61631. if (instance) {
  61632. radius = instance.radius;
  61633. }
  61634. if (options.radius !== undefined) {
  61635. radius = options.radius;
  61636. }
  61637. ;
  61638. var tessellation = options.tessellation || 64 | 0;
  61639. var radiusFunction = options.radiusFunction || null;
  61640. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61641. var invertUV = options.invertUV || false;
  61642. var updatable = options.updatable;
  61643. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61644. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61645. // tube geometry
  61646. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61647. var tangents = path3D.getTangents();
  61648. var normals = path3D.getNormals();
  61649. var distances = path3D.getDistances();
  61650. var pi2 = Math.PI * 2;
  61651. var step = pi2 / tessellation * arc;
  61652. var returnRadius = function () { return radius; };
  61653. var radiusFunctionFinal = radiusFunction || returnRadius;
  61654. var circlePath;
  61655. var rad;
  61656. var normal;
  61657. var rotated;
  61658. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61659. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61660. for (var i = 0; i < path.length; i++) {
  61661. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61662. circlePath = Array(); // current circle array
  61663. normal = normals[i]; // current normal
  61664. for (var t = 0; t < tessellation; t++) {
  61665. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61666. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61667. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61668. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61669. circlePath[t] = rotated;
  61670. }
  61671. circlePaths[index] = circlePath;
  61672. index++;
  61673. }
  61674. // cap
  61675. var capPath = function (nbPoints, pathIndex) {
  61676. var pointCap = Array();
  61677. for (var i = 0; i < nbPoints; i++) {
  61678. pointCap.push(path[pathIndex]);
  61679. }
  61680. return pointCap;
  61681. };
  61682. switch (cap) {
  61683. case BABYLON.Mesh.NO_CAP:
  61684. break;
  61685. case BABYLON.Mesh.CAP_START:
  61686. circlePaths[0] = capPath(tessellation, 0);
  61687. circlePaths[1] = circlePaths[2].slice(0);
  61688. break;
  61689. case BABYLON.Mesh.CAP_END:
  61690. circlePaths[index] = circlePaths[index - 1].slice(0);
  61691. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61692. break;
  61693. case BABYLON.Mesh.CAP_ALL:
  61694. circlePaths[0] = capPath(tessellation, 0);
  61695. circlePaths[1] = circlePaths[2].slice(0);
  61696. circlePaths[index] = circlePaths[index - 1].slice(0);
  61697. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61698. break;
  61699. default:
  61700. break;
  61701. }
  61702. return circlePaths;
  61703. };
  61704. var path3D;
  61705. var pathArray;
  61706. if (instance) { // tube update
  61707. var arc = options.arc || instance.arc;
  61708. path3D = (instance.path3D).update(path);
  61709. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61710. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61711. instance.path3D = path3D;
  61712. instance.pathArray = pathArray;
  61713. instance.arc = arc;
  61714. instance.radius = radius;
  61715. return instance;
  61716. }
  61717. // tube creation
  61718. path3D = new BABYLON.Path3D(path);
  61719. var newPathArray = new Array();
  61720. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61721. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61722. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61723. tube.pathArray = pathArray;
  61724. tube.path3D = path3D;
  61725. tube.tessellation = tessellation;
  61726. tube.cap = cap;
  61727. tube.arc = options.arc;
  61728. tube.radius = radius;
  61729. return tube;
  61730. };
  61731. /**
  61732. * Creates a polyhedron mesh
  61733. * * 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
  61734. * * The parameter `size` (positive float, default 1) sets the polygon size
  61735. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61736. * * 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`
  61737. * * 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
  61738. * * 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)`)
  61739. * * 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
  61740. * * 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
  61741. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61742. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61743. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61744. * @param name defines the name of the mesh
  61745. * @param options defines the options used to create the mesh
  61746. * @param scene defines the hosting scene
  61747. * @returns the polyhedron mesh
  61748. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61749. */
  61750. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61751. var polyhedron = new BABYLON.Mesh(name, scene);
  61752. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61753. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61754. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61755. vertexData.applyToMesh(polyhedron, options.updatable);
  61756. return polyhedron;
  61757. };
  61758. /**
  61759. * Creates a decal mesh.
  61760. * 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
  61761. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61762. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61763. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61764. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61765. * @param name defines the name of the mesh
  61766. * @param sourceMesh defines the mesh where the decal must be applied
  61767. * @param options defines the options used to create the mesh
  61768. * @param scene defines the hosting scene
  61769. * @returns the decal mesh
  61770. * @see http://doc.babylonjs.com/how_to/decals
  61771. */
  61772. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61773. var indices = sourceMesh.getIndices();
  61774. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61775. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61776. var position = options.position || BABYLON.Vector3.Zero();
  61777. var normal = options.normal || BABYLON.Vector3.Up();
  61778. var size = options.size || BABYLON.Vector3.One();
  61779. var angle = options.angle || 0;
  61780. // Getting correct rotation
  61781. if (!normal) {
  61782. var target = new BABYLON.Vector3(0, 0, 1);
  61783. var camera = sourceMesh.getScene().activeCamera;
  61784. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61785. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61786. }
  61787. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61788. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61789. var pitch = Math.atan2(normal.y, len);
  61790. // Matrix
  61791. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61792. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61793. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61794. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61795. var vertexData = new BABYLON.VertexData();
  61796. vertexData.indices = [];
  61797. vertexData.positions = [];
  61798. vertexData.normals = [];
  61799. vertexData.uvs = [];
  61800. var currentVertexDataIndex = 0;
  61801. var extractDecalVector3 = function (indexId) {
  61802. var result = new BABYLON.PositionNormalVertex();
  61803. if (!indices || !positions || !normals) {
  61804. return result;
  61805. }
  61806. var vertexId = indices[indexId];
  61807. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61808. // Send vector to decal local world
  61809. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61810. // Get normal
  61811. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61812. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61813. return result;
  61814. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61815. var clip = function (vertices, axis) {
  61816. if (vertices.length === 0) {
  61817. return vertices;
  61818. }
  61819. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61820. var clipVertices = function (v0, v1) {
  61821. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61822. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61823. };
  61824. var result = new Array();
  61825. for (var index = 0; index < vertices.length; index += 3) {
  61826. var v1Out;
  61827. var v2Out;
  61828. var v3Out;
  61829. var total = 0;
  61830. var nV1 = null;
  61831. var nV2 = null;
  61832. var nV3 = null;
  61833. var nV4 = null;
  61834. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61835. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61836. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61837. v1Out = d1 > 0;
  61838. v2Out = d2 > 0;
  61839. v3Out = d3 > 0;
  61840. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61841. switch (total) {
  61842. case 0:
  61843. result.push(vertices[index]);
  61844. result.push(vertices[index + 1]);
  61845. result.push(vertices[index + 2]);
  61846. break;
  61847. case 1:
  61848. if (v1Out) {
  61849. nV1 = vertices[index + 1];
  61850. nV2 = vertices[index + 2];
  61851. nV3 = clipVertices(vertices[index], nV1);
  61852. nV4 = clipVertices(vertices[index], nV2);
  61853. }
  61854. if (v2Out) {
  61855. nV1 = vertices[index];
  61856. nV2 = vertices[index + 2];
  61857. nV3 = clipVertices(vertices[index + 1], nV1);
  61858. nV4 = clipVertices(vertices[index + 1], nV2);
  61859. result.push(nV3);
  61860. result.push(nV2.clone());
  61861. result.push(nV1.clone());
  61862. result.push(nV2.clone());
  61863. result.push(nV3.clone());
  61864. result.push(nV4);
  61865. break;
  61866. }
  61867. if (v3Out) {
  61868. nV1 = vertices[index];
  61869. nV2 = vertices[index + 1];
  61870. nV3 = clipVertices(vertices[index + 2], nV1);
  61871. nV4 = clipVertices(vertices[index + 2], nV2);
  61872. }
  61873. if (nV1 && nV2 && nV3 && nV4) {
  61874. result.push(nV1.clone());
  61875. result.push(nV2.clone());
  61876. result.push(nV3);
  61877. result.push(nV4);
  61878. result.push(nV3.clone());
  61879. result.push(nV2.clone());
  61880. }
  61881. break;
  61882. case 2:
  61883. if (!v1Out) {
  61884. nV1 = vertices[index].clone();
  61885. nV2 = clipVertices(nV1, vertices[index + 1]);
  61886. nV3 = clipVertices(nV1, vertices[index + 2]);
  61887. result.push(nV1);
  61888. result.push(nV2);
  61889. result.push(nV3);
  61890. }
  61891. if (!v2Out) {
  61892. nV1 = vertices[index + 1].clone();
  61893. nV2 = clipVertices(nV1, vertices[index + 2]);
  61894. nV3 = clipVertices(nV1, vertices[index]);
  61895. result.push(nV1);
  61896. result.push(nV2);
  61897. result.push(nV3);
  61898. }
  61899. if (!v3Out) {
  61900. nV1 = vertices[index + 2].clone();
  61901. nV2 = clipVertices(nV1, vertices[index]);
  61902. nV3 = clipVertices(nV1, vertices[index + 1]);
  61903. result.push(nV1);
  61904. result.push(nV2);
  61905. result.push(nV3);
  61906. }
  61907. break;
  61908. case 3:
  61909. break;
  61910. }
  61911. }
  61912. return result;
  61913. };
  61914. for (var index = 0; index < indices.length; index += 3) {
  61915. var faceVertices = new Array();
  61916. faceVertices.push(extractDecalVector3(index));
  61917. faceVertices.push(extractDecalVector3(index + 1));
  61918. faceVertices.push(extractDecalVector3(index + 2));
  61919. // Clip
  61920. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61921. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61922. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61923. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61924. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61925. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61926. if (faceVertices.length === 0) {
  61927. continue;
  61928. }
  61929. // Add UVs and get back to world
  61930. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61931. var vertex = faceVertices[vIndex];
  61932. //TODO check for Int32Array | Uint32Array | Uint16Array
  61933. vertexData.indices.push(currentVertexDataIndex);
  61934. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61935. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61936. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61937. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61938. currentVertexDataIndex++;
  61939. }
  61940. }
  61941. // Return mesh
  61942. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61943. vertexData.applyToMesh(decal);
  61944. decal.position = position.clone();
  61945. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61946. return decal;
  61947. };
  61948. // Privates
  61949. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61950. // extrusion geometry
  61951. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61952. var tangents = path3D.getTangents();
  61953. var normals = path3D.getNormals();
  61954. var binormals = path3D.getBinormals();
  61955. var distances = path3D.getDistances();
  61956. var angle = 0;
  61957. var returnScale = function () { return scale !== null ? scale : 1; };
  61958. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61959. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61960. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61961. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61962. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61963. for (var i = 0; i < curve.length; i++) {
  61964. var shapePath = new Array();
  61965. var angleStep = rotate(i, distances[i]);
  61966. var scaleRatio = scl(i, distances[i]);
  61967. for (var p = 0; p < shape.length; p++) {
  61968. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61969. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61970. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61971. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61972. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61973. shapePath[p] = rotated;
  61974. }
  61975. shapePaths[index] = shapePath;
  61976. angle += angleStep;
  61977. index++;
  61978. }
  61979. // cap
  61980. var capPath = function (shapePath) {
  61981. var pointCap = Array();
  61982. var barycenter = BABYLON.Vector3.Zero();
  61983. var i;
  61984. for (i = 0; i < shapePath.length; i++) {
  61985. barycenter.addInPlace(shapePath[i]);
  61986. }
  61987. barycenter.scaleInPlace(1.0 / shapePath.length);
  61988. for (i = 0; i < shapePath.length; i++) {
  61989. pointCap.push(barycenter);
  61990. }
  61991. return pointCap;
  61992. };
  61993. switch (cap) {
  61994. case BABYLON.Mesh.NO_CAP:
  61995. break;
  61996. case BABYLON.Mesh.CAP_START:
  61997. shapePaths[0] = capPath(shapePaths[2]);
  61998. shapePaths[1] = shapePaths[2];
  61999. break;
  62000. case BABYLON.Mesh.CAP_END:
  62001. shapePaths[index] = shapePaths[index - 1];
  62002. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62003. break;
  62004. case BABYLON.Mesh.CAP_ALL:
  62005. shapePaths[0] = capPath(shapePaths[2]);
  62006. shapePaths[1] = shapePaths[2];
  62007. shapePaths[index] = shapePaths[index - 1];
  62008. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62009. break;
  62010. default:
  62011. break;
  62012. }
  62013. return shapePaths;
  62014. };
  62015. var path3D;
  62016. var pathArray;
  62017. if (instance) { // instance update
  62018. path3D = (instance.path3D).update(curve);
  62019. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62020. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62021. return instance;
  62022. }
  62023. // extruded shape creation
  62024. path3D = new BABYLON.Path3D(curve);
  62025. var newShapePaths = new Array();
  62026. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62027. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62028. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62029. extrudedGeneric.pathArray = pathArray;
  62030. extrudedGeneric.path3D = path3D;
  62031. extrudedGeneric.cap = cap;
  62032. return extrudedGeneric;
  62033. };
  62034. return MeshBuilder;
  62035. }());
  62036. BABYLON.MeshBuilder = MeshBuilder;
  62037. })(BABYLON || (BABYLON = {}));
  62038. //# sourceMappingURL=babylon.meshBuilder.js.map
  62039. var BABYLON;
  62040. (function (BABYLON) {
  62041. /**
  62042. * Draco compression (https://google.github.io/draco/)
  62043. *
  62044. * This class wraps the Draco module.
  62045. *
  62046. * **Encoder**
  62047. *
  62048. * The encoder is not currently implemented.
  62049. *
  62050. * **Decoder**
  62051. *
  62052. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62053. *
  62054. * To update the configuration, use the following code:
  62055. * ```javascript
  62056. * BABYLON.DracoCompression.Configuration = {
  62057. * decoder: {
  62058. * wasmUrl: "<url to the WebAssembly library>",
  62059. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62060. * fallbackUrl: "<url to the fallback JavaScript library>",
  62061. * }
  62062. * };
  62063. * ```
  62064. *
  62065. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  62066. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62067. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62068. *
  62069. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62070. * ```javascript
  62071. * var dracoCompression = new BABYLON.DracoCompression();
  62072. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62073. * [BABYLON.VertexBuffer.PositionKind]: 0
  62074. * });
  62075. * ```
  62076. *
  62077. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62078. */
  62079. var DracoCompression = /** @class */ (function () {
  62080. /**
  62081. * Constructor
  62082. */
  62083. function DracoCompression() {
  62084. }
  62085. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62086. /**
  62087. * Returns true if the decoder is available.
  62088. */
  62089. get: function () {
  62090. if (typeof DracoDecoderModule !== "undefined") {
  62091. return true;
  62092. }
  62093. var decoder = DracoCompression.Configuration.decoder;
  62094. if (decoder) {
  62095. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62096. return true;
  62097. }
  62098. if (decoder.fallbackUrl) {
  62099. return true;
  62100. }
  62101. }
  62102. return false;
  62103. },
  62104. enumerable: true,
  62105. configurable: true
  62106. });
  62107. /**
  62108. * Stop all async operations and release resources.
  62109. */
  62110. DracoCompression.prototype.dispose = function () {
  62111. };
  62112. /**
  62113. * Decode Draco compressed mesh data to vertex data.
  62114. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62115. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62116. * @returns A promise that resolves with the decoded vertex data
  62117. */
  62118. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62119. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62120. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62121. var module = wrappedModule.module;
  62122. var vertexData = new BABYLON.VertexData();
  62123. var buffer = new module.DecoderBuffer();
  62124. buffer.Init(dataView, dataView.byteLength);
  62125. var decoder = new module.Decoder();
  62126. var geometry;
  62127. var status;
  62128. try {
  62129. var type = decoder.GetEncodedGeometryType(buffer);
  62130. switch (type) {
  62131. case module.TRIANGULAR_MESH:
  62132. geometry = new module.Mesh();
  62133. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62134. break;
  62135. case module.POINT_CLOUD:
  62136. geometry = new module.PointCloud();
  62137. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62138. break;
  62139. default:
  62140. throw new Error("Invalid geometry type " + type);
  62141. }
  62142. if (!status.ok() || !geometry.ptr) {
  62143. throw new Error(status.error_msg());
  62144. }
  62145. var numPoints = geometry.num_points();
  62146. if (type === module.TRIANGULAR_MESH) {
  62147. var numFaces = geometry.num_faces();
  62148. var faceIndices = new module.DracoInt32Array();
  62149. try {
  62150. var indices = new Uint32Array(numFaces * 3);
  62151. for (var i = 0; i < numFaces; i++) {
  62152. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62153. var offset = i * 3;
  62154. indices[offset + 0] = faceIndices.GetValue(0);
  62155. indices[offset + 1] = faceIndices.GetValue(1);
  62156. indices[offset + 2] = faceIndices.GetValue(2);
  62157. }
  62158. vertexData.indices = indices;
  62159. }
  62160. finally {
  62161. module.destroy(faceIndices);
  62162. }
  62163. }
  62164. for (var kind in attributes) {
  62165. var uniqueId = attributes[kind];
  62166. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62167. var dracoData = new module.DracoFloat32Array();
  62168. try {
  62169. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62170. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62171. for (var i = 0; i < babylonData.length; i++) {
  62172. babylonData[i] = dracoData.GetValue(i);
  62173. }
  62174. vertexData.set(babylonData, kind);
  62175. }
  62176. finally {
  62177. module.destroy(dracoData);
  62178. }
  62179. }
  62180. }
  62181. finally {
  62182. if (geometry) {
  62183. module.destroy(geometry);
  62184. }
  62185. module.destroy(decoder);
  62186. module.destroy(buffer);
  62187. }
  62188. return vertexData;
  62189. });
  62190. };
  62191. DracoCompression._GetDecoderModule = function () {
  62192. if (!DracoCompression._DecoderModulePromise) {
  62193. var promise = null;
  62194. var config_1 = {};
  62195. if (typeof DracoDecoderModule !== "undefined") {
  62196. promise = Promise.resolve();
  62197. }
  62198. else {
  62199. var decoder = DracoCompression.Configuration.decoder;
  62200. if (decoder) {
  62201. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62202. promise = Promise.all([
  62203. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62204. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62205. config_1.wasmBinary = data;
  62206. })
  62207. ]);
  62208. }
  62209. else if (decoder.fallbackUrl) {
  62210. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62211. }
  62212. }
  62213. }
  62214. if (!promise) {
  62215. throw new Error("Draco decoder module is not available");
  62216. }
  62217. DracoCompression._DecoderModulePromise = promise.then(function () {
  62218. return new Promise(function (resolve) {
  62219. config_1.onModuleLoaded = function (decoderModule) {
  62220. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62221. resolve({ module: decoderModule });
  62222. };
  62223. DracoDecoderModule(config_1);
  62224. });
  62225. });
  62226. }
  62227. return DracoCompression._DecoderModulePromise;
  62228. };
  62229. DracoCompression._LoadScriptAsync = function (url) {
  62230. return new Promise(function (resolve, reject) {
  62231. BABYLON.Tools.LoadScript(url, function () {
  62232. resolve();
  62233. }, function (message) {
  62234. reject(new Error(message));
  62235. });
  62236. });
  62237. };
  62238. DracoCompression._LoadFileAsync = function (url) {
  62239. return new Promise(function (resolve, reject) {
  62240. BABYLON.Tools.LoadFile(url, function (data) {
  62241. resolve(data);
  62242. }, undefined, undefined, true, function (request, exception) {
  62243. reject(exception);
  62244. });
  62245. });
  62246. };
  62247. /**
  62248. * The configuration. Defaults to the following urls:
  62249. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62250. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62251. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62252. */
  62253. DracoCompression.Configuration = {
  62254. decoder: {
  62255. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62256. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62257. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62258. }
  62259. };
  62260. return DracoCompression;
  62261. }());
  62262. BABYLON.DracoCompression = DracoCompression;
  62263. })(BABYLON || (BABYLON = {}));
  62264. //# sourceMappingURL=babylon.dracoCompression.js.map
  62265. var BABYLON;
  62266. (function (BABYLON) {
  62267. var AudioEngine = /** @class */ (function () {
  62268. function AudioEngine() {
  62269. this._audioContext = null;
  62270. this._audioContextInitialized = false;
  62271. this.canUseWebAudio = false;
  62272. this.WarnedWebAudioUnsupported = false;
  62273. this.unlocked = false;
  62274. this.isMP3supported = false;
  62275. this.isOGGsupported = false;
  62276. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62277. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62278. this.canUseWebAudio = true;
  62279. }
  62280. var audioElem = document.createElement('audio');
  62281. try {
  62282. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62283. this.isMP3supported = true;
  62284. }
  62285. }
  62286. catch (e) {
  62287. // protect error during capability check.
  62288. }
  62289. try {
  62290. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62291. this.isOGGsupported = true;
  62292. }
  62293. }
  62294. catch (e) {
  62295. // protect error during capability check.
  62296. }
  62297. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62298. this._unlockiOSaudio();
  62299. }
  62300. else {
  62301. this.unlocked = true;
  62302. }
  62303. }
  62304. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62305. get: function () {
  62306. if (!this._audioContextInitialized) {
  62307. this._initializeAudioContext();
  62308. }
  62309. return this._audioContext;
  62310. },
  62311. enumerable: true,
  62312. configurable: true
  62313. });
  62314. AudioEngine.prototype._unlockiOSaudio = function () {
  62315. var _this = this;
  62316. var unlockaudio = function () {
  62317. if (!_this.audioContext) {
  62318. return;
  62319. }
  62320. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62321. var source = _this.audioContext.createBufferSource();
  62322. source.buffer = buffer;
  62323. source.connect(_this.audioContext.destination);
  62324. source.start(0);
  62325. setTimeout(function () {
  62326. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62327. _this.unlocked = true;
  62328. window.removeEventListener('touchend', unlockaudio, false);
  62329. if (_this.onAudioUnlocked) {
  62330. _this.onAudioUnlocked();
  62331. }
  62332. }
  62333. }, 0);
  62334. };
  62335. window.addEventListener('touchend', unlockaudio, false);
  62336. };
  62337. AudioEngine.prototype._initializeAudioContext = function () {
  62338. try {
  62339. if (this.canUseWebAudio) {
  62340. this._audioContext = new AudioContext();
  62341. // create a global volume gain node
  62342. this.masterGain = this._audioContext.createGain();
  62343. this.masterGain.gain.value = 1;
  62344. this.masterGain.connect(this._audioContext.destination);
  62345. this._audioContextInitialized = true;
  62346. }
  62347. }
  62348. catch (e) {
  62349. this.canUseWebAudio = false;
  62350. BABYLON.Tools.Error("Web Audio: " + e.message);
  62351. }
  62352. };
  62353. AudioEngine.prototype.dispose = function () {
  62354. if (this.canUseWebAudio && this._audioContextInitialized) {
  62355. if (this._connectedAnalyser && this._audioContext) {
  62356. this._connectedAnalyser.stopDebugCanvas();
  62357. this._connectedAnalyser.dispose();
  62358. this.masterGain.disconnect();
  62359. this.masterGain.connect(this._audioContext.destination);
  62360. this._connectedAnalyser = null;
  62361. }
  62362. this.masterGain.gain.value = 1;
  62363. }
  62364. this.WarnedWebAudioUnsupported = false;
  62365. };
  62366. AudioEngine.prototype.getGlobalVolume = function () {
  62367. if (this.canUseWebAudio && this._audioContextInitialized) {
  62368. return this.masterGain.gain.value;
  62369. }
  62370. else {
  62371. return -1;
  62372. }
  62373. };
  62374. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62375. if (this.canUseWebAudio && this._audioContextInitialized) {
  62376. this.masterGain.gain.value = newVolume;
  62377. }
  62378. };
  62379. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62380. if (this._connectedAnalyser) {
  62381. this._connectedAnalyser.stopDebugCanvas();
  62382. }
  62383. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62384. this._connectedAnalyser = analyser;
  62385. this.masterGain.disconnect();
  62386. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62387. }
  62388. };
  62389. return AudioEngine;
  62390. }());
  62391. BABYLON.AudioEngine = AudioEngine;
  62392. })(BABYLON || (BABYLON = {}));
  62393. //# sourceMappingURL=babylon.audioEngine.js.map
  62394. var BABYLON;
  62395. (function (BABYLON) {
  62396. var Sound = /** @class */ (function () {
  62397. /**
  62398. * Create a sound and attach it to a scene
  62399. * @param name Name of your sound
  62400. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62401. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62402. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62403. */
  62404. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62405. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62406. var _this = this;
  62407. this.autoplay = false;
  62408. this.loop = false;
  62409. this.useCustomAttenuation = false;
  62410. this.spatialSound = false;
  62411. this.refDistance = 1;
  62412. this.rolloffFactor = 1;
  62413. this.maxDistance = 100;
  62414. this.distanceModel = "linear";
  62415. this._panningModel = "equalpower";
  62416. this._playbackRate = 1;
  62417. this._streaming = false;
  62418. this._startTime = 0;
  62419. this._startOffset = 0;
  62420. this._position = BABYLON.Vector3.Zero();
  62421. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62422. this._volume = 1;
  62423. this._isReadyToPlay = false;
  62424. this.isPlaying = false;
  62425. this.isPaused = false;
  62426. this._isDirectional = false;
  62427. // Used if you'd like to create a directional sound.
  62428. // If not set, the sound will be omnidirectional
  62429. this._coneInnerAngle = 360;
  62430. this._coneOuterAngle = 360;
  62431. this._coneOuterGain = 0;
  62432. this._isOutputConnected = false;
  62433. this._urlType = "Unknown";
  62434. this.name = name;
  62435. this._scene = scene;
  62436. this._readyToPlayCallback = readyToPlayCallback;
  62437. // Default custom attenuation function is a linear attenuation
  62438. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62439. if (currentDistance < maxDistance) {
  62440. return currentVolume * (1 - currentDistance / maxDistance);
  62441. }
  62442. else {
  62443. return 0;
  62444. }
  62445. };
  62446. if (options) {
  62447. this.autoplay = options.autoplay || false;
  62448. this.loop = options.loop || false;
  62449. // if volume === 0, we need another way to check this option
  62450. if (options.volume !== undefined) {
  62451. this._volume = options.volume;
  62452. }
  62453. this.spatialSound = options.spatialSound || false;
  62454. this.maxDistance = options.maxDistance || 100;
  62455. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62456. this.rolloffFactor = options.rolloffFactor || 1;
  62457. this.refDistance = options.refDistance || 1;
  62458. this.distanceModel = options.distanceModel || "linear";
  62459. this._playbackRate = options.playbackRate || 1;
  62460. this._streaming = options.streaming || false;
  62461. }
  62462. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62463. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62464. this._soundGain.gain.value = this._volume;
  62465. this._inputAudioNode = this._soundGain;
  62466. this._ouputAudioNode = this._soundGain;
  62467. if (this.spatialSound) {
  62468. this._createSpatialParameters();
  62469. }
  62470. this._scene.mainSoundTrack.AddSound(this);
  62471. var validParameter = true;
  62472. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62473. if (urlOrArrayBuffer) {
  62474. try {
  62475. if (typeof (urlOrArrayBuffer) === "string")
  62476. this._urlType = "String";
  62477. if (Array.isArray(urlOrArrayBuffer))
  62478. this._urlType = "Array";
  62479. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62480. this._urlType = "ArrayBuffer";
  62481. var urls = [];
  62482. var codecSupportedFound = false;
  62483. switch (this._urlType) {
  62484. case "ArrayBuffer":
  62485. if (urlOrArrayBuffer.byteLength > 0) {
  62486. codecSupportedFound = true;
  62487. this._soundLoaded(urlOrArrayBuffer);
  62488. }
  62489. break;
  62490. case "String":
  62491. urls.push(urlOrArrayBuffer);
  62492. case "Array":
  62493. if (urls.length === 0)
  62494. urls = urlOrArrayBuffer;
  62495. // If we found a supported format, we load it immediately and stop the loop
  62496. for (var i = 0; i < urls.length; i++) {
  62497. var url = urls[i];
  62498. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62499. codecSupportedFound = true;
  62500. }
  62501. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62502. codecSupportedFound = true;
  62503. }
  62504. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62505. codecSupportedFound = true;
  62506. }
  62507. if (url.indexOf("blob:") !== -1) {
  62508. codecSupportedFound = true;
  62509. }
  62510. if (codecSupportedFound) {
  62511. // Loading sound using XHR2
  62512. if (!this._streaming) {
  62513. this._scene._loadFile(url, function (data) {
  62514. _this._soundLoaded(data);
  62515. }, undefined, true, true, function (exception) {
  62516. if (exception) {
  62517. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62518. }
  62519. BABYLON.Tools.Error("Sound creation aborted.");
  62520. _this._scene.mainSoundTrack.RemoveSound(_this);
  62521. });
  62522. }
  62523. // Streaming sound using HTML5 Audio tag
  62524. else {
  62525. this._htmlAudioElement = new Audio(url);
  62526. this._htmlAudioElement.controls = false;
  62527. this._htmlAudioElement.loop = this.loop;
  62528. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62529. this._htmlAudioElement.preload = "auto";
  62530. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62531. _this._isReadyToPlay = true;
  62532. if (_this.autoplay) {
  62533. _this.play();
  62534. }
  62535. if (_this._readyToPlayCallback) {
  62536. _this._readyToPlayCallback();
  62537. }
  62538. });
  62539. document.body.appendChild(this._htmlAudioElement);
  62540. }
  62541. break;
  62542. }
  62543. }
  62544. break;
  62545. default:
  62546. validParameter = false;
  62547. break;
  62548. }
  62549. if (!validParameter) {
  62550. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62551. }
  62552. else {
  62553. if (!codecSupportedFound) {
  62554. this._isReadyToPlay = true;
  62555. // Simulating a ready to play event to avoid breaking code path
  62556. if (this._readyToPlayCallback) {
  62557. window.setTimeout(function () {
  62558. if (_this._readyToPlayCallback) {
  62559. _this._readyToPlayCallback();
  62560. }
  62561. }, 1000);
  62562. }
  62563. }
  62564. }
  62565. }
  62566. catch (ex) {
  62567. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62568. this._scene.mainSoundTrack.RemoveSound(this);
  62569. }
  62570. }
  62571. }
  62572. else {
  62573. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62574. this._scene.mainSoundTrack.AddSound(this);
  62575. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62576. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62577. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62578. }
  62579. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62580. if (this._readyToPlayCallback) {
  62581. window.setTimeout(function () {
  62582. if (_this._readyToPlayCallback) {
  62583. _this._readyToPlayCallback();
  62584. }
  62585. }, 1000);
  62586. }
  62587. }
  62588. }
  62589. Sound.prototype.dispose = function () {
  62590. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62591. if (this.isPlaying) {
  62592. this.stop();
  62593. }
  62594. this._isReadyToPlay = false;
  62595. if (this.soundTrackId === -1) {
  62596. this._scene.mainSoundTrack.RemoveSound(this);
  62597. }
  62598. else {
  62599. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62600. }
  62601. if (this._soundGain) {
  62602. this._soundGain.disconnect();
  62603. this._soundGain = null;
  62604. }
  62605. if (this._soundPanner) {
  62606. this._soundPanner.disconnect();
  62607. this._soundPanner = null;
  62608. }
  62609. if (this._soundSource) {
  62610. this._soundSource.disconnect();
  62611. this._soundSource = null;
  62612. }
  62613. this._audioBuffer = null;
  62614. if (this._htmlAudioElement) {
  62615. this._htmlAudioElement.pause();
  62616. this._htmlAudioElement.src = "";
  62617. document.body.removeChild(this._htmlAudioElement);
  62618. }
  62619. if (this._connectedMesh && this._registerFunc) {
  62620. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62621. this._connectedMesh = null;
  62622. }
  62623. }
  62624. };
  62625. Sound.prototype.isReady = function () {
  62626. return this._isReadyToPlay;
  62627. };
  62628. Sound.prototype._soundLoaded = function (audioData) {
  62629. var _this = this;
  62630. if (!BABYLON.Engine.audioEngine.audioContext) {
  62631. return;
  62632. }
  62633. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62634. _this._audioBuffer = buffer;
  62635. _this._isReadyToPlay = true;
  62636. if (_this.autoplay) {
  62637. _this.play();
  62638. }
  62639. if (_this._readyToPlayCallback) {
  62640. _this._readyToPlayCallback();
  62641. }
  62642. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62643. };
  62644. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62645. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62646. this._audioBuffer = audioBuffer;
  62647. this._isReadyToPlay = true;
  62648. }
  62649. };
  62650. Sound.prototype.updateOptions = function (options) {
  62651. if (options) {
  62652. this.loop = options.loop || this.loop;
  62653. this.maxDistance = options.maxDistance || this.maxDistance;
  62654. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62655. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62656. this.refDistance = options.refDistance || this.refDistance;
  62657. this.distanceModel = options.distanceModel || this.distanceModel;
  62658. this._playbackRate = options.playbackRate || this._playbackRate;
  62659. this._updateSpatialParameters();
  62660. if (this.isPlaying) {
  62661. if (this._streaming) {
  62662. this._htmlAudioElement.playbackRate = this._playbackRate;
  62663. }
  62664. else {
  62665. if (this._soundSource) {
  62666. this._soundSource.playbackRate.value = this._playbackRate;
  62667. }
  62668. }
  62669. }
  62670. }
  62671. };
  62672. Sound.prototype._createSpatialParameters = function () {
  62673. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62674. if (this._scene.headphone) {
  62675. this._panningModel = "HRTF";
  62676. }
  62677. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62678. this._updateSpatialParameters();
  62679. this._soundPanner.connect(this._ouputAudioNode);
  62680. this._inputAudioNode = this._soundPanner;
  62681. }
  62682. };
  62683. Sound.prototype._updateSpatialParameters = function () {
  62684. if (this.spatialSound && this._soundPanner) {
  62685. if (this.useCustomAttenuation) {
  62686. // Tricks to disable in a way embedded Web Audio attenuation
  62687. this._soundPanner.distanceModel = "linear";
  62688. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62689. this._soundPanner.refDistance = 1;
  62690. this._soundPanner.rolloffFactor = 1;
  62691. this._soundPanner.panningModel = this._panningModel;
  62692. }
  62693. else {
  62694. this._soundPanner.distanceModel = this.distanceModel;
  62695. this._soundPanner.maxDistance = this.maxDistance;
  62696. this._soundPanner.refDistance = this.refDistance;
  62697. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62698. this._soundPanner.panningModel = this._panningModel;
  62699. }
  62700. }
  62701. };
  62702. Sound.prototype.switchPanningModelToHRTF = function () {
  62703. this._panningModel = "HRTF";
  62704. this._switchPanningModel();
  62705. };
  62706. Sound.prototype.switchPanningModelToEqualPower = function () {
  62707. this._panningModel = "equalpower";
  62708. this._switchPanningModel();
  62709. };
  62710. Sound.prototype._switchPanningModel = function () {
  62711. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62712. this._soundPanner.panningModel = this._panningModel;
  62713. }
  62714. };
  62715. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62716. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62717. if (this._isOutputConnected) {
  62718. this._ouputAudioNode.disconnect();
  62719. }
  62720. this._ouputAudioNode.connect(soundTrackAudioNode);
  62721. this._isOutputConnected = true;
  62722. }
  62723. };
  62724. /**
  62725. * Transform this sound into a directional source
  62726. * @param coneInnerAngle Size of the inner cone in degree
  62727. * @param coneOuterAngle Size of the outer cone in degree
  62728. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62729. */
  62730. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62731. if (coneOuterAngle < coneInnerAngle) {
  62732. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62733. return;
  62734. }
  62735. this._coneInnerAngle = coneInnerAngle;
  62736. this._coneOuterAngle = coneOuterAngle;
  62737. this._coneOuterGain = coneOuterGain;
  62738. this._isDirectional = true;
  62739. if (this.isPlaying && this.loop) {
  62740. this.stop();
  62741. this.play();
  62742. }
  62743. };
  62744. Sound.prototype.setPosition = function (newPosition) {
  62745. this._position = newPosition;
  62746. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62747. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62748. }
  62749. };
  62750. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62751. this._localDirection = newLocalDirection;
  62752. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62753. this._updateDirection();
  62754. }
  62755. };
  62756. Sound.prototype._updateDirection = function () {
  62757. if (!this._connectedMesh || !this._soundPanner) {
  62758. return;
  62759. }
  62760. var mat = this._connectedMesh.getWorldMatrix();
  62761. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62762. direction.normalize();
  62763. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62764. };
  62765. Sound.prototype.updateDistanceFromListener = function () {
  62766. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62767. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62768. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62769. }
  62770. };
  62771. Sound.prototype.setAttenuationFunction = function (callback) {
  62772. this._customAttenuationFunction = callback;
  62773. };
  62774. /**
  62775. * Play the sound
  62776. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62777. * @param offset (optional) Start the sound setting it at a specific time
  62778. */
  62779. Sound.prototype.play = function (time, offset) {
  62780. var _this = this;
  62781. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62782. try {
  62783. if (this._startOffset < 0) {
  62784. time = -this._startOffset;
  62785. this._startOffset = 0;
  62786. }
  62787. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62788. if (!this._soundSource || !this._streamingSource) {
  62789. if (this.spatialSound && this._soundPanner) {
  62790. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62791. if (this._isDirectional) {
  62792. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62793. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62794. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62795. if (this._connectedMesh) {
  62796. this._updateDirection();
  62797. }
  62798. else {
  62799. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62800. }
  62801. }
  62802. }
  62803. }
  62804. if (this._streaming) {
  62805. if (!this._streamingSource) {
  62806. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62807. this._htmlAudioElement.onended = function () { _this._onended(); };
  62808. this._htmlAudioElement.playbackRate = this._playbackRate;
  62809. }
  62810. this._streamingSource.disconnect();
  62811. this._streamingSource.connect(this._inputAudioNode);
  62812. this._htmlAudioElement.play();
  62813. }
  62814. else {
  62815. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62816. this._soundSource.buffer = this._audioBuffer;
  62817. this._soundSource.connect(this._inputAudioNode);
  62818. this._soundSource.loop = this.loop;
  62819. this._soundSource.playbackRate.value = this._playbackRate;
  62820. this._soundSource.onended = function () { _this._onended(); };
  62821. if (this._soundSource.buffer) {
  62822. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62823. }
  62824. }
  62825. this._startTime = startTime;
  62826. this.isPlaying = true;
  62827. this.isPaused = false;
  62828. }
  62829. catch (ex) {
  62830. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62831. }
  62832. }
  62833. };
  62834. Sound.prototype._onended = function () {
  62835. this.isPlaying = false;
  62836. if (this.onended) {
  62837. this.onended();
  62838. }
  62839. };
  62840. /**
  62841. * Stop the sound
  62842. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62843. */
  62844. Sound.prototype.stop = function (time) {
  62845. if (this.isPlaying) {
  62846. if (this._streaming) {
  62847. this._htmlAudioElement.pause();
  62848. // Test needed for Firefox or it will generate an Invalid State Error
  62849. if (this._htmlAudioElement.currentTime > 0) {
  62850. this._htmlAudioElement.currentTime = 0;
  62851. }
  62852. }
  62853. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62854. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62855. this._soundSource.stop(stopTime);
  62856. this._soundSource.onended = function () { };
  62857. if (!this.isPaused) {
  62858. this._startOffset = 0;
  62859. }
  62860. }
  62861. this.isPlaying = false;
  62862. }
  62863. };
  62864. Sound.prototype.pause = function () {
  62865. if (this.isPlaying) {
  62866. this.isPaused = true;
  62867. if (this._streaming) {
  62868. this._htmlAudioElement.pause();
  62869. }
  62870. else if (BABYLON.Engine.audioEngine.audioContext) {
  62871. this.stop(0);
  62872. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62873. }
  62874. }
  62875. };
  62876. Sound.prototype.setVolume = function (newVolume, time) {
  62877. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62878. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62879. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62880. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62881. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62882. }
  62883. else {
  62884. this._soundGain.gain.value = newVolume;
  62885. }
  62886. }
  62887. this._volume = newVolume;
  62888. };
  62889. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62890. this._playbackRate = newPlaybackRate;
  62891. if (this.isPlaying) {
  62892. if (this._streaming) {
  62893. this._htmlAudioElement.playbackRate = this._playbackRate;
  62894. }
  62895. else if (this._soundSource) {
  62896. this._soundSource.playbackRate.value = this._playbackRate;
  62897. }
  62898. }
  62899. };
  62900. Sound.prototype.getVolume = function () {
  62901. return this._volume;
  62902. };
  62903. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62904. var _this = this;
  62905. if (this._connectedMesh && this._registerFunc) {
  62906. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62907. this._registerFunc = null;
  62908. }
  62909. this._connectedMesh = meshToConnectTo;
  62910. if (!this.spatialSound) {
  62911. this.spatialSound = true;
  62912. this._createSpatialParameters();
  62913. if (this.isPlaying && this.loop) {
  62914. this.stop();
  62915. this.play();
  62916. }
  62917. }
  62918. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62919. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62920. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62921. };
  62922. Sound.prototype.detachFromMesh = function () {
  62923. if (this._connectedMesh && this._registerFunc) {
  62924. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62925. this._registerFunc = null;
  62926. this._connectedMesh = null;
  62927. }
  62928. };
  62929. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62930. if (!node.getBoundingInfo) {
  62931. return;
  62932. }
  62933. var mesh = node;
  62934. var boundingInfo = mesh.getBoundingInfo();
  62935. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62936. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62937. this._updateDirection();
  62938. }
  62939. };
  62940. Sound.prototype.clone = function () {
  62941. var _this = this;
  62942. if (!this._streaming) {
  62943. var setBufferAndRun = function () {
  62944. if (_this._isReadyToPlay) {
  62945. clonedSound._audioBuffer = _this.getAudioBuffer();
  62946. clonedSound._isReadyToPlay = true;
  62947. if (clonedSound.autoplay) {
  62948. clonedSound.play();
  62949. }
  62950. }
  62951. else {
  62952. window.setTimeout(setBufferAndRun, 300);
  62953. }
  62954. };
  62955. var currentOptions = {
  62956. autoplay: this.autoplay, loop: this.loop,
  62957. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62958. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62959. refDistance: this.refDistance, distanceModel: this.distanceModel
  62960. };
  62961. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62962. if (this.useCustomAttenuation) {
  62963. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62964. }
  62965. clonedSound.setPosition(this._position);
  62966. clonedSound.setPlaybackRate(this._playbackRate);
  62967. setBufferAndRun();
  62968. return clonedSound;
  62969. }
  62970. // Can't clone a streaming sound
  62971. else {
  62972. return null;
  62973. }
  62974. };
  62975. Sound.prototype.getAudioBuffer = function () {
  62976. return this._audioBuffer;
  62977. };
  62978. Sound.prototype.serialize = function () {
  62979. var serializationObject = {
  62980. name: this.name,
  62981. url: this.name,
  62982. autoplay: this.autoplay,
  62983. loop: this.loop,
  62984. volume: this._volume,
  62985. spatialSound: this.spatialSound,
  62986. maxDistance: this.maxDistance,
  62987. rolloffFactor: this.rolloffFactor,
  62988. refDistance: this.refDistance,
  62989. distanceModel: this.distanceModel,
  62990. playbackRate: this._playbackRate,
  62991. panningModel: this._panningModel,
  62992. soundTrackId: this.soundTrackId
  62993. };
  62994. if (this.spatialSound) {
  62995. if (this._connectedMesh)
  62996. serializationObject.connectedMeshId = this._connectedMesh.id;
  62997. serializationObject.position = this._position.asArray();
  62998. serializationObject.refDistance = this.refDistance;
  62999. serializationObject.distanceModel = this.distanceModel;
  63000. serializationObject.isDirectional = this._isDirectional;
  63001. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63002. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63003. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63004. serializationObject.coneOuterGain = this._coneOuterGain;
  63005. }
  63006. return serializationObject;
  63007. };
  63008. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63009. var soundName = parsedSound.name;
  63010. var soundUrl;
  63011. if (parsedSound.url) {
  63012. soundUrl = rootUrl + parsedSound.url;
  63013. }
  63014. else {
  63015. soundUrl = rootUrl + soundName;
  63016. }
  63017. var options = {
  63018. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63019. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63020. rolloffFactor: parsedSound.rolloffFactor,
  63021. refDistance: parsedSound.refDistance,
  63022. distanceModel: parsedSound.distanceModel,
  63023. playbackRate: parsedSound.playbackRate
  63024. };
  63025. var newSound;
  63026. if (!sourceSound) {
  63027. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63028. scene._addPendingData(newSound);
  63029. }
  63030. else {
  63031. var setBufferAndRun = function () {
  63032. if (sourceSound._isReadyToPlay) {
  63033. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63034. newSound._isReadyToPlay = true;
  63035. if (newSound.autoplay) {
  63036. newSound.play();
  63037. }
  63038. }
  63039. else {
  63040. window.setTimeout(setBufferAndRun, 300);
  63041. }
  63042. };
  63043. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63044. setBufferAndRun();
  63045. }
  63046. if (parsedSound.position) {
  63047. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63048. newSound.setPosition(soundPosition);
  63049. }
  63050. if (parsedSound.isDirectional) {
  63051. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63052. if (parsedSound.localDirectionToMesh) {
  63053. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63054. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63055. }
  63056. }
  63057. if (parsedSound.connectedMeshId) {
  63058. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63059. if (connectedMesh) {
  63060. newSound.attachToMesh(connectedMesh);
  63061. }
  63062. }
  63063. return newSound;
  63064. };
  63065. return Sound;
  63066. }());
  63067. BABYLON.Sound = Sound;
  63068. })(BABYLON || (BABYLON = {}));
  63069. //# sourceMappingURL=babylon.sound.js.map
  63070. var BABYLON;
  63071. (function (BABYLON) {
  63072. var SoundTrack = /** @class */ (function () {
  63073. function SoundTrack(scene, options) {
  63074. this.id = -1;
  63075. this._isMainTrack = false;
  63076. this._isInitialized = false;
  63077. this._scene = scene;
  63078. this.soundCollection = new Array();
  63079. this._options = options;
  63080. if (!this._isMainTrack) {
  63081. this._scene.soundTracks.push(this);
  63082. this.id = this._scene.soundTracks.length - 1;
  63083. }
  63084. }
  63085. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63086. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63087. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63088. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63089. if (this._options) {
  63090. if (this._options.volume) {
  63091. this._outputAudioNode.gain.value = this._options.volume;
  63092. }
  63093. if (this._options.mainTrack) {
  63094. this._isMainTrack = this._options.mainTrack;
  63095. }
  63096. }
  63097. this._isInitialized = true;
  63098. }
  63099. };
  63100. SoundTrack.prototype.dispose = function () {
  63101. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63102. if (this._connectedAnalyser) {
  63103. this._connectedAnalyser.stopDebugCanvas();
  63104. }
  63105. while (this.soundCollection.length) {
  63106. this.soundCollection[0].dispose();
  63107. }
  63108. if (this._outputAudioNode) {
  63109. this._outputAudioNode.disconnect();
  63110. }
  63111. this._outputAudioNode = null;
  63112. }
  63113. };
  63114. SoundTrack.prototype.AddSound = function (sound) {
  63115. if (!this._isInitialized) {
  63116. this._initializeSoundTrackAudioGraph();
  63117. }
  63118. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63119. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63120. }
  63121. if (sound.soundTrackId) {
  63122. if (sound.soundTrackId === -1) {
  63123. this._scene.mainSoundTrack.RemoveSound(sound);
  63124. }
  63125. else {
  63126. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63127. }
  63128. }
  63129. this.soundCollection.push(sound);
  63130. sound.soundTrackId = this.id;
  63131. };
  63132. SoundTrack.prototype.RemoveSound = function (sound) {
  63133. var index = this.soundCollection.indexOf(sound);
  63134. if (index !== -1) {
  63135. this.soundCollection.splice(index, 1);
  63136. }
  63137. };
  63138. SoundTrack.prototype.setVolume = function (newVolume) {
  63139. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63140. this._outputAudioNode.gain.value = newVolume;
  63141. }
  63142. };
  63143. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63144. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63145. for (var i = 0; i < this.soundCollection.length; i++) {
  63146. this.soundCollection[i].switchPanningModelToHRTF();
  63147. }
  63148. }
  63149. };
  63150. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63151. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63152. for (var i = 0; i < this.soundCollection.length; i++) {
  63153. this.soundCollection[i].switchPanningModelToEqualPower();
  63154. }
  63155. }
  63156. };
  63157. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63158. if (this._connectedAnalyser) {
  63159. this._connectedAnalyser.stopDebugCanvas();
  63160. }
  63161. this._connectedAnalyser = analyser;
  63162. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63163. this._outputAudioNode.disconnect();
  63164. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63165. }
  63166. };
  63167. return SoundTrack;
  63168. }());
  63169. BABYLON.SoundTrack = SoundTrack;
  63170. })(BABYLON || (BABYLON = {}));
  63171. //# sourceMappingURL=babylon.soundtrack.js.map
  63172. var BABYLON;
  63173. (function (BABYLON) {
  63174. /**
  63175. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63176. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63177. */
  63178. var Analyser = /** @class */ (function () {
  63179. /**
  63180. * Creates a new analyser
  63181. * @param scene defines hosting scene
  63182. */
  63183. function Analyser(scene) {
  63184. /**
  63185. * Gets or sets the smoothing
  63186. * @ignorenaming
  63187. */
  63188. this.SMOOTHING = 0.75;
  63189. /**
  63190. * Gets or sets the FFT table size
  63191. * @ignorenaming
  63192. */
  63193. this.FFT_SIZE = 512;
  63194. /**
  63195. * Gets or sets the bar graph amplitude
  63196. * @ignorenaming
  63197. */
  63198. this.BARGRAPHAMPLITUDE = 256;
  63199. /**
  63200. * Gets or sets the position of the debug canvas
  63201. * @ignorenaming
  63202. */
  63203. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63204. /**
  63205. * Gets or sets the debug canvas size
  63206. * @ignorenaming
  63207. */
  63208. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63209. this._scene = scene;
  63210. this._audioEngine = BABYLON.Engine.audioEngine;
  63211. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63212. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63213. this._webAudioAnalyser.minDecibels = -140;
  63214. this._webAudioAnalyser.maxDecibels = 0;
  63215. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63216. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63217. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63218. }
  63219. }
  63220. /**
  63221. * Get the number of data values you will have to play with for the visualization
  63222. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63223. * @returns a number
  63224. */
  63225. Analyser.prototype.getFrequencyBinCount = function () {
  63226. if (this._audioEngine.canUseWebAudio) {
  63227. return this._webAudioAnalyser.frequencyBinCount;
  63228. }
  63229. else {
  63230. return 0;
  63231. }
  63232. };
  63233. /**
  63234. * Gets the current frequency data as a byte array
  63235. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63236. * @returns a Uint8Array
  63237. */
  63238. Analyser.prototype.getByteFrequencyData = function () {
  63239. if (this._audioEngine.canUseWebAudio) {
  63240. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63241. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63242. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63243. }
  63244. return this._byteFreqs;
  63245. };
  63246. /**
  63247. * Gets the current waveform as a byte array
  63248. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63249. * @returns a Uint8Array
  63250. */
  63251. Analyser.prototype.getByteTimeDomainData = function () {
  63252. if (this._audioEngine.canUseWebAudio) {
  63253. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63254. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63255. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63256. }
  63257. return this._byteTime;
  63258. };
  63259. /**
  63260. * Gets the current frequency data as a float array
  63261. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63262. * @returns a Float32Array
  63263. */
  63264. Analyser.prototype.getFloatFrequencyData = function () {
  63265. if (this._audioEngine.canUseWebAudio) {
  63266. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63267. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63268. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63269. }
  63270. return this._floatFreqs;
  63271. };
  63272. /**
  63273. * Renders the debug canvas
  63274. */
  63275. Analyser.prototype.drawDebugCanvas = function () {
  63276. var _this = this;
  63277. if (this._audioEngine.canUseWebAudio) {
  63278. if (!this._debugCanvas) {
  63279. this._debugCanvas = document.createElement("canvas");
  63280. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63281. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63282. this._debugCanvas.style.position = "absolute";
  63283. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63284. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63285. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63286. document.body.appendChild(this._debugCanvas);
  63287. this._registerFunc = function () {
  63288. _this.drawDebugCanvas();
  63289. };
  63290. this._scene.registerBeforeRender(this._registerFunc);
  63291. }
  63292. if (this._registerFunc && this._debugCanvasContext) {
  63293. var workingArray = this.getByteFrequencyData();
  63294. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63295. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63296. // Draw the frequency domain chart.
  63297. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63298. var value = workingArray[i];
  63299. var percent = value / this.BARGRAPHAMPLITUDE;
  63300. var height = this.DEBUGCANVASSIZE.height * percent;
  63301. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63302. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63303. var hue = i / this.getFrequencyBinCount() * 360;
  63304. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63305. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63306. }
  63307. }
  63308. }
  63309. };
  63310. /**
  63311. * Stops rendering the debug canvas and removes it
  63312. */
  63313. Analyser.prototype.stopDebugCanvas = function () {
  63314. if (this._debugCanvas) {
  63315. if (this._registerFunc) {
  63316. this._scene.unregisterBeforeRender(this._registerFunc);
  63317. this._registerFunc = null;
  63318. }
  63319. document.body.removeChild(this._debugCanvas);
  63320. this._debugCanvas = null;
  63321. this._debugCanvasContext = null;
  63322. }
  63323. };
  63324. /**
  63325. * Connects two audio nodes
  63326. * @param inputAudioNode defines first node to connect
  63327. * @param outputAudioNode defines second node to connect
  63328. */
  63329. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63330. if (this._audioEngine.canUseWebAudio) {
  63331. inputAudioNode.connect(this._webAudioAnalyser);
  63332. this._webAudioAnalyser.connect(outputAudioNode);
  63333. }
  63334. };
  63335. /**
  63336. * Releases all associated resources
  63337. */
  63338. Analyser.prototype.dispose = function () {
  63339. if (this._audioEngine.canUseWebAudio) {
  63340. this._webAudioAnalyser.disconnect();
  63341. }
  63342. };
  63343. return Analyser;
  63344. }());
  63345. BABYLON.Analyser = Analyser;
  63346. })(BABYLON || (BABYLON = {}));
  63347. //# sourceMappingURL=babylon.analyser.js.map
  63348. var BABYLON;
  63349. (function (BABYLON) {
  63350. var CubeTexture = /** @class */ (function (_super) {
  63351. __extends(CubeTexture, _super);
  63352. /**
  63353. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63354. * as prefiltered data.
  63355. * @param rootUrl defines the url of the texture or the root name of the six images
  63356. * @param scene defines the scene the texture is attached to
  63357. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63358. * @param noMipmap defines if mipmaps should be created or not
  63359. * @param files defines the six files to load for the different faces
  63360. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63361. * @param onError defines a callback triggered in case of error during load
  63362. * @param format defines the internal format to use for the texture once loaded
  63363. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63364. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63365. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63366. * @return the cube texture
  63367. */
  63368. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials) {
  63369. if (extensions === void 0) { extensions = null; }
  63370. if (noMipmap === void 0) { noMipmap = false; }
  63371. if (files === void 0) { files = null; }
  63372. if (onLoad === void 0) { onLoad = null; }
  63373. if (onError === void 0) { onError = null; }
  63374. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63375. if (prefiltered === void 0) { prefiltered = false; }
  63376. if (forcedExtension === void 0) { forcedExtension = null; }
  63377. if (createPolynomials === void 0) { createPolynomials = false; }
  63378. var _this = _super.call(this, scene) || this;
  63379. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63380. /**
  63381. * Gets or sets the center of the bounding box associated with the cube texture
  63382. * It must define where the camera used to render the texture was set
  63383. */
  63384. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63385. _this._rotationY = 0;
  63386. _this.name = rootUrl;
  63387. _this.url = rootUrl;
  63388. _this._noMipmap = noMipmap;
  63389. _this.hasAlpha = false;
  63390. _this._format = format;
  63391. _this._prefiltered = prefiltered;
  63392. _this.isCube = true;
  63393. _this._textureMatrix = BABYLON.Matrix.Identity();
  63394. _this._createPolynomials = createPolynomials;
  63395. if (prefiltered) {
  63396. _this.gammaSpace = false;
  63397. }
  63398. if (!rootUrl && !files) {
  63399. return _this;
  63400. }
  63401. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63402. var lastDot = rootUrl.lastIndexOf(".");
  63403. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63404. var isDDS = (extension === ".dds");
  63405. if (!files) {
  63406. if (!isDDS && !extensions) {
  63407. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63408. }
  63409. files = [];
  63410. if (extensions) {
  63411. for (var index = 0; index < extensions.length; index++) {
  63412. files.push(rootUrl + extensions[index]);
  63413. }
  63414. }
  63415. }
  63416. _this._files = files;
  63417. if (!_this._texture) {
  63418. if (!scene.useDelayedTextureLoading) {
  63419. if (prefiltered) {
  63420. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63421. }
  63422. else {
  63423. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63424. }
  63425. }
  63426. else {
  63427. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63428. }
  63429. }
  63430. else if (onLoad) {
  63431. if (_this._texture.isReady) {
  63432. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63433. }
  63434. else {
  63435. _this._texture.onLoadedObservable.add(onLoad);
  63436. }
  63437. }
  63438. return _this;
  63439. }
  63440. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63441. get: function () {
  63442. return this._boundingBoxSize;
  63443. },
  63444. /**
  63445. * Gets or sets the size of the bounding box associated with the cube texture
  63446. * When defined, the cubemap will switch to local mode
  63447. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63448. * @example https://www.babylonjs-playground.com/#RNASML
  63449. */
  63450. set: function (value) {
  63451. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63452. return;
  63453. }
  63454. this._boundingBoxSize = value;
  63455. var scene = this.getScene();
  63456. if (scene) {
  63457. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63458. }
  63459. },
  63460. enumerable: true,
  63461. configurable: true
  63462. });
  63463. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63464. /**
  63465. * Gets texture matrix rotation angle around Y axis radians.
  63466. */
  63467. get: function () {
  63468. return this._rotationY;
  63469. },
  63470. /**
  63471. * Sets texture matrix rotation angle around Y axis in radians.
  63472. */
  63473. set: function (value) {
  63474. this._rotationY = value;
  63475. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63476. },
  63477. enumerable: true,
  63478. configurable: true
  63479. });
  63480. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63481. var rootUrlKey = "";
  63482. files.forEach(function (url) { return rootUrlKey += url; });
  63483. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63484. };
  63485. /**
  63486. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63487. * @param url defines the url of the prefiltered texture
  63488. * @param scene defines the scene the texture is attached to
  63489. * @param forcedExtension defines the extension of the file if different from the url
  63490. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63491. * @return the prefiltered texture
  63492. */
  63493. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63494. if (forcedExtension === void 0) { forcedExtension = null; }
  63495. if (createPolynomials === void 0) { createPolynomials = true; }
  63496. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63497. };
  63498. // Methods
  63499. CubeTexture.prototype.delayLoad = function () {
  63500. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63501. return;
  63502. }
  63503. var scene = this.getScene();
  63504. if (!scene) {
  63505. return;
  63506. }
  63507. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63508. this._texture = this._getFromCache(this.url, this._noMipmap);
  63509. if (!this._texture) {
  63510. if (this._prefiltered) {
  63511. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63512. }
  63513. else {
  63514. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63515. }
  63516. }
  63517. };
  63518. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63519. return this._textureMatrix;
  63520. };
  63521. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63522. this._textureMatrix = value;
  63523. };
  63524. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63525. var texture = BABYLON.SerializationHelper.Parse(function () {
  63526. var prefiltered = false;
  63527. if (parsedTexture.prefiltered) {
  63528. prefiltered = parsedTexture.prefiltered;
  63529. }
  63530. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63531. }, parsedTexture, scene);
  63532. // Local Cubemaps
  63533. if (parsedTexture.boundingBoxPosition) {
  63534. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63535. }
  63536. if (parsedTexture.boundingBoxSize) {
  63537. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63538. }
  63539. // Animations
  63540. if (parsedTexture.animations) {
  63541. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63542. var parsedAnimation = parsedTexture.animations[animationIndex];
  63543. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63544. }
  63545. }
  63546. return texture;
  63547. };
  63548. CubeTexture.prototype.clone = function () {
  63549. var _this = this;
  63550. return BABYLON.SerializationHelper.Clone(function () {
  63551. var scene = _this.getScene();
  63552. if (!scene) {
  63553. return _this;
  63554. }
  63555. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63556. }, this);
  63557. };
  63558. __decorate([
  63559. BABYLON.serialize("rotationY")
  63560. ], CubeTexture.prototype, "_rotationY", void 0);
  63561. return CubeTexture;
  63562. }(BABYLON.BaseTexture));
  63563. BABYLON.CubeTexture = CubeTexture;
  63564. })(BABYLON || (BABYLON = {}));
  63565. //# sourceMappingURL=babylon.cubeTexture.js.map
  63566. var BABYLON;
  63567. (function (BABYLON) {
  63568. var RenderTargetTexture = /** @class */ (function (_super) {
  63569. __extends(RenderTargetTexture, _super);
  63570. /**
  63571. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63572. * or used a shadow, depth texture...
  63573. * @param name The friendly name of the texture
  63574. * @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)
  63575. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63576. * @param generateMipMaps True if mip maps need to be generated after render.
  63577. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63578. * @param type The type of the buffer in the RTT (int, half float, float...)
  63579. * @param isCube True if a cube texture needs to be created
  63580. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63581. * @param generateDepthBuffer True to generate a depth buffer
  63582. * @param generateStencilBuffer True to generate a stencil buffer
  63583. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63584. */
  63585. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63586. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63587. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63588. if (isCube === void 0) { isCube = false; }
  63589. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63590. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63591. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63592. if (isMulti === void 0) { isMulti = false; }
  63593. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63594. _this.isCube = isCube;
  63595. /**
  63596. * Use this list to define the list of mesh you want to render.
  63597. */
  63598. _this.renderList = new Array();
  63599. _this.renderParticles = true;
  63600. _this.renderSprites = false;
  63601. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63602. _this.ignoreCameraViewport = false;
  63603. // Events
  63604. /**
  63605. * An event triggered when the texture is unbind.
  63606. */
  63607. _this.onBeforeBindObservable = new BABYLON.Observable();
  63608. /**
  63609. * An event triggered when the texture is unbind.
  63610. */
  63611. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63612. /**
  63613. * An event triggered before rendering the texture
  63614. */
  63615. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63616. /**
  63617. * An event triggered after rendering the texture
  63618. */
  63619. _this.onAfterRenderObservable = new BABYLON.Observable();
  63620. /**
  63621. * An event triggered after the texture clear
  63622. */
  63623. _this.onClearObservable = new BABYLON.Observable();
  63624. _this._currentRefreshId = -1;
  63625. _this._refreshRate = 1;
  63626. _this._samples = 1;
  63627. /**
  63628. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63629. * It must define where the camera used to render the texture is set
  63630. */
  63631. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63632. scene = _this.getScene();
  63633. if (!scene) {
  63634. return _this;
  63635. }
  63636. _this._engine = scene.getEngine();
  63637. _this.name = name;
  63638. _this.isRenderTarget = true;
  63639. _this._initialSizeParameter = size;
  63640. _this._processSizeParameter(size);
  63641. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63642. });
  63643. _this._generateMipMaps = generateMipMaps ? true : false;
  63644. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63645. // Rendering groups
  63646. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63647. if (isMulti) {
  63648. return _this;
  63649. }
  63650. _this._renderTargetOptions = {
  63651. generateMipMaps: generateMipMaps,
  63652. type: type,
  63653. samplingMode: samplingMode,
  63654. generateDepthBuffer: generateDepthBuffer,
  63655. generateStencilBuffer: generateStencilBuffer
  63656. };
  63657. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63658. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63659. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63660. }
  63661. if (isCube) {
  63662. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63663. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63664. _this._textureMatrix = BABYLON.Matrix.Identity();
  63665. }
  63666. else {
  63667. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63668. }
  63669. return _this;
  63670. }
  63671. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63672. get: function () {
  63673. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63674. },
  63675. enumerable: true,
  63676. configurable: true
  63677. });
  63678. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63679. get: function () {
  63680. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63681. },
  63682. enumerable: true,
  63683. configurable: true
  63684. });
  63685. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63686. get: function () {
  63687. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63688. },
  63689. enumerable: true,
  63690. configurable: true
  63691. });
  63692. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63693. set: function (callback) {
  63694. if (this._onAfterUnbindObserver) {
  63695. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63696. }
  63697. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63698. },
  63699. enumerable: true,
  63700. configurable: true
  63701. });
  63702. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63703. set: function (callback) {
  63704. if (this._onBeforeRenderObserver) {
  63705. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63706. }
  63707. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63708. },
  63709. enumerable: true,
  63710. configurable: true
  63711. });
  63712. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63713. set: function (callback) {
  63714. if (this._onAfterRenderObserver) {
  63715. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63716. }
  63717. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63718. },
  63719. enumerable: true,
  63720. configurable: true
  63721. });
  63722. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63723. set: function (callback) {
  63724. if (this._onClearObserver) {
  63725. this.onClearObservable.remove(this._onClearObserver);
  63726. }
  63727. this._onClearObserver = this.onClearObservable.add(callback);
  63728. },
  63729. enumerable: true,
  63730. configurable: true
  63731. });
  63732. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63733. get: function () {
  63734. return this._renderTargetOptions;
  63735. },
  63736. enumerable: true,
  63737. configurable: true
  63738. });
  63739. RenderTargetTexture.prototype._onRatioRescale = function () {
  63740. if (this._sizeRatio) {
  63741. this.resize(this._initialSizeParameter);
  63742. }
  63743. };
  63744. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63745. get: function () {
  63746. return this._boundingBoxSize;
  63747. },
  63748. /**
  63749. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63750. * When defined, the cubemap will switch to local mode
  63751. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63752. * @example https://www.babylonjs-playground.com/#RNASML
  63753. */
  63754. set: function (value) {
  63755. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63756. return;
  63757. }
  63758. this._boundingBoxSize = value;
  63759. var scene = this.getScene();
  63760. if (scene) {
  63761. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63762. }
  63763. },
  63764. enumerable: true,
  63765. configurable: true
  63766. });
  63767. /**
  63768. * Creates a depth stencil texture.
  63769. * This is only available in WebGL 2 or with the depth texture extension available.
  63770. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63771. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63772. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63773. */
  63774. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63775. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63776. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63777. if (generateStencil === void 0) { generateStencil = false; }
  63778. if (!this.getScene()) {
  63779. return;
  63780. }
  63781. var engine = this.getScene().getEngine();
  63782. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63783. bilinearFiltering: bilinearFiltering,
  63784. comparisonFunction: comparisonFunction,
  63785. generateStencil: generateStencil,
  63786. isCube: this.isCube
  63787. });
  63788. engine.setFrameBufferDepthStencilTexture(this);
  63789. };
  63790. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63791. if (size.ratio) {
  63792. this._sizeRatio = size.ratio;
  63793. this._size = {
  63794. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63795. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63796. };
  63797. }
  63798. else {
  63799. this._size = size;
  63800. }
  63801. };
  63802. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63803. get: function () {
  63804. return this._samples;
  63805. },
  63806. set: function (value) {
  63807. if (this._samples === value) {
  63808. return;
  63809. }
  63810. var scene = this.getScene();
  63811. if (!scene) {
  63812. return;
  63813. }
  63814. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63815. },
  63816. enumerable: true,
  63817. configurable: true
  63818. });
  63819. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63820. this._currentRefreshId = -1;
  63821. };
  63822. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63823. get: function () {
  63824. return this._refreshRate;
  63825. },
  63826. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63827. set: function (value) {
  63828. this._refreshRate = value;
  63829. this.resetRefreshCounter();
  63830. },
  63831. enumerable: true,
  63832. configurable: true
  63833. });
  63834. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63835. if (!this._postProcessManager) {
  63836. var scene = this.getScene();
  63837. if (!scene) {
  63838. return;
  63839. }
  63840. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63841. this._postProcesses = new Array();
  63842. }
  63843. this._postProcesses.push(postProcess);
  63844. this._postProcesses[0].autoClear = false;
  63845. };
  63846. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63847. if (!this._postProcesses) {
  63848. return;
  63849. }
  63850. if (dispose) {
  63851. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63852. var postProcess = _a[_i];
  63853. postProcess.dispose();
  63854. }
  63855. }
  63856. this._postProcesses = [];
  63857. };
  63858. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63859. if (!this._postProcesses) {
  63860. return;
  63861. }
  63862. var index = this._postProcesses.indexOf(postProcess);
  63863. if (index === -1) {
  63864. return;
  63865. }
  63866. this._postProcesses.splice(index, 1);
  63867. if (this._postProcesses.length > 0) {
  63868. this._postProcesses[0].autoClear = false;
  63869. }
  63870. };
  63871. RenderTargetTexture.prototype._shouldRender = function () {
  63872. if (this._currentRefreshId === -1) { // At least render once
  63873. this._currentRefreshId = 1;
  63874. return true;
  63875. }
  63876. if (this.refreshRate === this._currentRefreshId) {
  63877. this._currentRefreshId = 1;
  63878. return true;
  63879. }
  63880. this._currentRefreshId++;
  63881. return false;
  63882. };
  63883. RenderTargetTexture.prototype.getRenderSize = function () {
  63884. if (this._size.width) {
  63885. return this._size.width;
  63886. }
  63887. return this._size;
  63888. };
  63889. RenderTargetTexture.prototype.getRenderWidth = function () {
  63890. if (this._size.width) {
  63891. return this._size.width;
  63892. }
  63893. return this._size;
  63894. };
  63895. RenderTargetTexture.prototype.getRenderHeight = function () {
  63896. if (this._size.width) {
  63897. return this._size.height;
  63898. }
  63899. return this._size;
  63900. };
  63901. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63902. get: function () {
  63903. return true;
  63904. },
  63905. enumerable: true,
  63906. configurable: true
  63907. });
  63908. RenderTargetTexture.prototype.scale = function (ratio) {
  63909. var newSize = this.getRenderSize() * ratio;
  63910. this.resize(newSize);
  63911. };
  63912. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63913. if (this.isCube) {
  63914. return this._textureMatrix;
  63915. }
  63916. return _super.prototype.getReflectionTextureMatrix.call(this);
  63917. };
  63918. RenderTargetTexture.prototype.resize = function (size) {
  63919. this.releaseInternalTexture();
  63920. var scene = this.getScene();
  63921. if (!scene) {
  63922. return;
  63923. }
  63924. this._processSizeParameter(size);
  63925. if (this.isCube) {
  63926. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63927. }
  63928. else {
  63929. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63930. }
  63931. };
  63932. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63933. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63934. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63935. var scene = this.getScene();
  63936. if (!scene) {
  63937. return;
  63938. }
  63939. var engine = scene.getEngine();
  63940. if (this.useCameraPostProcesses !== undefined) {
  63941. useCameraPostProcess = this.useCameraPostProcesses;
  63942. }
  63943. if (this._waitingRenderList) {
  63944. this.renderList = [];
  63945. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63946. var id = this._waitingRenderList[index];
  63947. var mesh_1 = scene.getMeshByID(id);
  63948. if (mesh_1) {
  63949. this.renderList.push(mesh_1);
  63950. }
  63951. }
  63952. delete this._waitingRenderList;
  63953. }
  63954. // Is predicate defined?
  63955. if (this.renderListPredicate) {
  63956. if (this.renderList) {
  63957. this.renderList.splice(0); // Clear previous renderList
  63958. }
  63959. else {
  63960. this.renderList = [];
  63961. }
  63962. var scene = this.getScene();
  63963. if (!scene) {
  63964. return;
  63965. }
  63966. var sceneMeshes = scene.meshes;
  63967. for (var index = 0; index < sceneMeshes.length; index++) {
  63968. var mesh = sceneMeshes[index];
  63969. if (this.renderListPredicate(mesh)) {
  63970. this.renderList.push(mesh);
  63971. }
  63972. }
  63973. }
  63974. this.onBeforeBindObservable.notifyObservers(this);
  63975. // Set custom projection.
  63976. // Needs to be before binding to prevent changing the aspect ratio.
  63977. var camera;
  63978. if (this.activeCamera) {
  63979. camera = this.activeCamera;
  63980. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63981. if (this.activeCamera !== scene.activeCamera) {
  63982. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63983. }
  63984. }
  63985. else {
  63986. camera = scene.activeCamera;
  63987. if (camera) {
  63988. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63989. }
  63990. }
  63991. // Prepare renderingManager
  63992. this._renderingManager.reset();
  63993. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63994. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63995. var sceneRenderId = scene.getRenderId();
  63996. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63997. var mesh = currentRenderList[meshIndex];
  63998. if (mesh) {
  63999. if (!mesh.isReady(this.refreshRate === 0)) {
  64000. this.resetRefreshCounter();
  64001. continue;
  64002. }
  64003. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64004. var isMasked = void 0;
  64005. if (!this.renderList && camera) {
  64006. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64007. }
  64008. else {
  64009. isMasked = false;
  64010. }
  64011. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64012. mesh._activate(sceneRenderId);
  64013. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64014. var subMesh = mesh.subMeshes[subIndex];
  64015. scene._activeIndices.addCount(subMesh.indexCount, false);
  64016. this._renderingManager.dispatch(subMesh, mesh);
  64017. }
  64018. }
  64019. }
  64020. }
  64021. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64022. var particleSystem = scene.particleSystems[particleIndex];
  64023. var emitter = particleSystem.emitter;
  64024. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64025. continue;
  64026. }
  64027. if (currentRenderList.indexOf(emitter) >= 0) {
  64028. this._renderingManager.dispatchParticles(particleSystem);
  64029. }
  64030. }
  64031. if (this.isCube) {
  64032. for (var face = 0; face < 6; face++) {
  64033. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64034. scene.incrementRenderId();
  64035. scene.resetCachedMaterial();
  64036. }
  64037. }
  64038. else {
  64039. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64040. }
  64041. this.onAfterUnbindObservable.notifyObservers(this);
  64042. if (scene.activeCamera) {
  64043. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64044. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64045. }
  64046. engine.setViewport(scene.activeCamera.viewport);
  64047. }
  64048. scene.resetCachedMaterial();
  64049. };
  64050. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64051. var minimum = 128;
  64052. var x = renderDimension * scale;
  64053. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64054. // Ensure we don't exceed the render dimension (while staying POT)
  64055. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64056. };
  64057. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64058. var _this = this;
  64059. if (!this._texture) {
  64060. return;
  64061. }
  64062. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64063. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64064. });
  64065. };
  64066. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64067. var scene = this.getScene();
  64068. if (!scene) {
  64069. return;
  64070. }
  64071. var engine = scene.getEngine();
  64072. if (!this._texture) {
  64073. return;
  64074. }
  64075. // Bind
  64076. if (this._postProcessManager) {
  64077. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64078. }
  64079. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64080. if (this._texture) {
  64081. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64082. }
  64083. }
  64084. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64085. // Clear
  64086. if (this.onClearObservable.hasObservers()) {
  64087. this.onClearObservable.notifyObservers(engine);
  64088. }
  64089. else {
  64090. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64091. }
  64092. if (!this._doNotChangeAspectRatio) {
  64093. scene.updateTransformMatrix(true);
  64094. }
  64095. // Render
  64096. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64097. if (this._postProcessManager) {
  64098. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64099. }
  64100. else if (useCameraPostProcess) {
  64101. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64102. }
  64103. if (!this._doNotChangeAspectRatio) {
  64104. scene.updateTransformMatrix(true);
  64105. }
  64106. // Dump ?
  64107. if (dumpForDebug) {
  64108. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64109. }
  64110. // Unbind
  64111. if (!this.isCube || faceIndex === 5) {
  64112. if (this.isCube) {
  64113. if (faceIndex === 5) {
  64114. engine.generateMipMapsForCubemap(this._texture);
  64115. }
  64116. }
  64117. this.unbindFrameBuffer(engine, faceIndex);
  64118. }
  64119. else {
  64120. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64121. }
  64122. };
  64123. /**
  64124. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64125. * This allowed control for front to back rendering or reversly depending of the special needs.
  64126. *
  64127. * @param renderingGroupId The rendering group id corresponding to its index
  64128. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64129. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64130. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64131. */
  64132. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64133. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64134. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64135. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64136. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64137. };
  64138. /**
  64139. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64140. *
  64141. * @param renderingGroupId The rendering group id corresponding to its index
  64142. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64143. */
  64144. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64145. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64146. };
  64147. RenderTargetTexture.prototype.clone = function () {
  64148. var textureSize = this.getSize();
  64149. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  64150. // Base texture
  64151. newTexture.hasAlpha = this.hasAlpha;
  64152. newTexture.level = this.level;
  64153. // RenderTarget Texture
  64154. newTexture.coordinatesMode = this.coordinatesMode;
  64155. if (this.renderList) {
  64156. newTexture.renderList = this.renderList.slice(0);
  64157. }
  64158. return newTexture;
  64159. };
  64160. RenderTargetTexture.prototype.serialize = function () {
  64161. if (!this.name) {
  64162. return null;
  64163. }
  64164. var serializationObject = _super.prototype.serialize.call(this);
  64165. serializationObject.renderTargetSize = this.getRenderSize();
  64166. serializationObject.renderList = [];
  64167. if (this.renderList) {
  64168. for (var index = 0; index < this.renderList.length; index++) {
  64169. serializationObject.renderList.push(this.renderList[index].id);
  64170. }
  64171. }
  64172. return serializationObject;
  64173. };
  64174. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64175. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64176. var objBuffer = this.getInternalTexture();
  64177. var scene = this.getScene();
  64178. if (objBuffer && scene) {
  64179. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64180. }
  64181. };
  64182. RenderTargetTexture.prototype.dispose = function () {
  64183. if (this._postProcessManager) {
  64184. this._postProcessManager.dispose();
  64185. this._postProcessManager = null;
  64186. }
  64187. this.clearPostProcesses(true);
  64188. if (this._resizeObserver) {
  64189. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64190. this._resizeObserver = null;
  64191. }
  64192. this.renderList = null;
  64193. // Remove from custom render targets
  64194. var scene = this.getScene();
  64195. if (!scene) {
  64196. return;
  64197. }
  64198. var index = scene.customRenderTargets.indexOf(this);
  64199. if (index >= 0) {
  64200. scene.customRenderTargets.splice(index, 1);
  64201. }
  64202. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64203. var camera = _a[_i];
  64204. index = camera.customRenderTargets.indexOf(this);
  64205. if (index >= 0) {
  64206. camera.customRenderTargets.splice(index, 1);
  64207. }
  64208. }
  64209. _super.prototype.dispose.call(this);
  64210. };
  64211. RenderTargetTexture.prototype._rebuild = function () {
  64212. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64213. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64214. }
  64215. if (this._postProcessManager) {
  64216. this._postProcessManager._rebuild();
  64217. }
  64218. };
  64219. /**
  64220. * Clear the info related to rendering groups preventing retention point in material dispose.
  64221. */
  64222. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64223. if (this._renderingManager) {
  64224. this._renderingManager.freeRenderingGroups();
  64225. }
  64226. };
  64227. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64228. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64229. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64230. return RenderTargetTexture;
  64231. }(BABYLON.Texture));
  64232. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64233. })(BABYLON || (BABYLON = {}));
  64234. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64235. var BABYLON;
  64236. (function (BABYLON) {
  64237. ;
  64238. var MultiRenderTarget = /** @class */ (function (_super) {
  64239. __extends(MultiRenderTarget, _super);
  64240. function MultiRenderTarget(name, size, count, scene, options) {
  64241. var _this = this;
  64242. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64243. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64244. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64245. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64246. _this._engine = scene.getEngine();
  64247. if (!_this.isSupported) {
  64248. _this.dispose();
  64249. return;
  64250. }
  64251. var types = [];
  64252. var samplingModes = [];
  64253. for (var i = 0; i < count; i++) {
  64254. if (options && options.types && options.types[i] !== undefined) {
  64255. types.push(options.types[i]);
  64256. }
  64257. else {
  64258. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64259. }
  64260. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64261. samplingModes.push(options.samplingModes[i]);
  64262. }
  64263. else {
  64264. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64265. }
  64266. }
  64267. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64268. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64269. _this._size = size;
  64270. _this._multiRenderTargetOptions = {
  64271. samplingModes: samplingModes,
  64272. generateMipMaps: generateMipMaps,
  64273. generateDepthBuffer: generateDepthBuffer,
  64274. generateStencilBuffer: generateStencilBuffer,
  64275. generateDepthTexture: generateDepthTexture,
  64276. types: types,
  64277. textureCount: count
  64278. };
  64279. _this._createInternalTextures();
  64280. _this._createTextures();
  64281. return _this;
  64282. }
  64283. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64284. get: function () {
  64285. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64286. },
  64287. enumerable: true,
  64288. configurable: true
  64289. });
  64290. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64291. get: function () {
  64292. return this._textures;
  64293. },
  64294. enumerable: true,
  64295. configurable: true
  64296. });
  64297. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64298. get: function () {
  64299. return this._textures[this._textures.length - 1];
  64300. },
  64301. enumerable: true,
  64302. configurable: true
  64303. });
  64304. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64305. set: function (wrap) {
  64306. if (this._textures) {
  64307. for (var i = 0; i < this._textures.length; i++) {
  64308. this._textures[i].wrapU = wrap;
  64309. }
  64310. }
  64311. },
  64312. enumerable: true,
  64313. configurable: true
  64314. });
  64315. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64316. set: function (wrap) {
  64317. if (this._textures) {
  64318. for (var i = 0; i < this._textures.length; i++) {
  64319. this._textures[i].wrapV = wrap;
  64320. }
  64321. }
  64322. },
  64323. enumerable: true,
  64324. configurable: true
  64325. });
  64326. MultiRenderTarget.prototype._rebuild = function () {
  64327. this.releaseInternalTextures();
  64328. this._createInternalTextures();
  64329. for (var i = 0; i < this._internalTextures.length; i++) {
  64330. var texture = this._textures[i];
  64331. texture._texture = this._internalTextures[i];
  64332. }
  64333. // Keeps references to frame buffer and stencil/depth buffer
  64334. this._texture = this._internalTextures[0];
  64335. };
  64336. MultiRenderTarget.prototype._createInternalTextures = function () {
  64337. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64338. };
  64339. MultiRenderTarget.prototype._createTextures = function () {
  64340. this._textures = [];
  64341. for (var i = 0; i < this._internalTextures.length; i++) {
  64342. var texture = new BABYLON.Texture(null, this.getScene());
  64343. texture._texture = this._internalTextures[i];
  64344. this._textures.push(texture);
  64345. }
  64346. // Keeps references to frame buffer and stencil/depth buffer
  64347. this._texture = this._internalTextures[0];
  64348. };
  64349. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64350. get: function () {
  64351. return this._samples;
  64352. },
  64353. set: function (value) {
  64354. if (this._samples === value) {
  64355. return;
  64356. }
  64357. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64358. },
  64359. enumerable: true,
  64360. configurable: true
  64361. });
  64362. MultiRenderTarget.prototype.resize = function (size) {
  64363. this.releaseInternalTextures();
  64364. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64365. this._createInternalTextures();
  64366. };
  64367. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64368. var _this = this;
  64369. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64370. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64371. });
  64372. };
  64373. MultiRenderTarget.prototype.dispose = function () {
  64374. this.releaseInternalTextures();
  64375. _super.prototype.dispose.call(this);
  64376. };
  64377. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64378. if (!this._internalTextures) {
  64379. return;
  64380. }
  64381. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64382. if (this._internalTextures[i] !== undefined) {
  64383. this._internalTextures[i].dispose();
  64384. this._internalTextures.splice(i, 1);
  64385. }
  64386. }
  64387. };
  64388. return MultiRenderTarget;
  64389. }(BABYLON.RenderTargetTexture));
  64390. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64391. })(BABYLON || (BABYLON = {}));
  64392. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64393. var BABYLON;
  64394. (function (BABYLON) {
  64395. var MirrorTexture = /** @class */ (function (_super) {
  64396. __extends(MirrorTexture, _super);
  64397. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64398. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64399. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64400. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64401. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64402. _this.scene = scene;
  64403. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64404. _this._transformMatrix = BABYLON.Matrix.Zero();
  64405. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64406. _this._adaptiveBlurKernel = 0;
  64407. _this._blurKernelX = 0;
  64408. _this._blurKernelY = 0;
  64409. _this._blurRatio = 1.0;
  64410. _this.ignoreCameraViewport = true;
  64411. _this._updateGammaSpace();
  64412. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64413. _this._updateGammaSpace;
  64414. });
  64415. _this.onBeforeRenderObservable.add(function () {
  64416. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64417. _this._savedViewMatrix = scene.getViewMatrix();
  64418. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64419. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64420. scene.clipPlane = _this.mirrorPlane;
  64421. scene.getEngine().cullBackFaces = false;
  64422. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64423. });
  64424. _this.onAfterRenderObservable.add(function () {
  64425. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64426. scene.getEngine().cullBackFaces = true;
  64427. scene._mirroredCameraPosition = null;
  64428. delete scene.clipPlane;
  64429. });
  64430. return _this;
  64431. }
  64432. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64433. get: function () {
  64434. return this._blurRatio;
  64435. },
  64436. set: function (value) {
  64437. if (this._blurRatio === value) {
  64438. return;
  64439. }
  64440. this._blurRatio = value;
  64441. this._preparePostProcesses();
  64442. },
  64443. enumerable: true,
  64444. configurable: true
  64445. });
  64446. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64447. set: function (value) {
  64448. this._adaptiveBlurKernel = value;
  64449. this._autoComputeBlurKernel();
  64450. },
  64451. enumerable: true,
  64452. configurable: true
  64453. });
  64454. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64455. set: function (value) {
  64456. this.blurKernelX = value;
  64457. this.blurKernelY = value;
  64458. },
  64459. enumerable: true,
  64460. configurable: true
  64461. });
  64462. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64463. get: function () {
  64464. return this._blurKernelX;
  64465. },
  64466. set: function (value) {
  64467. if (this._blurKernelX === value) {
  64468. return;
  64469. }
  64470. this._blurKernelX = value;
  64471. this._preparePostProcesses();
  64472. },
  64473. enumerable: true,
  64474. configurable: true
  64475. });
  64476. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64477. get: function () {
  64478. return this._blurKernelY;
  64479. },
  64480. set: function (value) {
  64481. if (this._blurKernelY === value) {
  64482. return;
  64483. }
  64484. this._blurKernelY = value;
  64485. this._preparePostProcesses();
  64486. },
  64487. enumerable: true,
  64488. configurable: true
  64489. });
  64490. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64491. var engine = this.getScene().getEngine();
  64492. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64493. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64494. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64495. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64496. };
  64497. MirrorTexture.prototype._onRatioRescale = function () {
  64498. if (this._sizeRatio) {
  64499. this.resize(this._initialSizeParameter);
  64500. if (!this._adaptiveBlurKernel) {
  64501. this._preparePostProcesses();
  64502. }
  64503. }
  64504. if (this._adaptiveBlurKernel) {
  64505. this._autoComputeBlurKernel();
  64506. }
  64507. };
  64508. MirrorTexture.prototype._updateGammaSpace = function () {
  64509. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64510. };
  64511. MirrorTexture.prototype._preparePostProcesses = function () {
  64512. this.clearPostProcesses(true);
  64513. if (this._blurKernelX && this._blurKernelY) {
  64514. var engine = this.getScene().getEngine();
  64515. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64516. 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);
  64517. this._blurX.autoClear = false;
  64518. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64519. this._blurX.inputTexture = this._texture;
  64520. }
  64521. else {
  64522. this._blurX.alwaysForcePOT = true;
  64523. }
  64524. 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);
  64525. this._blurY.autoClear = false;
  64526. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64527. this.addPostProcess(this._blurX);
  64528. this.addPostProcess(this._blurY);
  64529. }
  64530. else {
  64531. if (this._blurY) {
  64532. this.removePostProcess(this._blurY);
  64533. this._blurY.dispose();
  64534. this._blurY = null;
  64535. }
  64536. if (this._blurX) {
  64537. this.removePostProcess(this._blurX);
  64538. this._blurX.dispose();
  64539. this._blurX = null;
  64540. }
  64541. }
  64542. };
  64543. MirrorTexture.prototype.clone = function () {
  64544. var scene = this.getScene();
  64545. if (!scene) {
  64546. return this;
  64547. }
  64548. var textureSize = this.getSize();
  64549. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64550. // Base texture
  64551. newTexture.hasAlpha = this.hasAlpha;
  64552. newTexture.level = this.level;
  64553. // Mirror Texture
  64554. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64555. if (this.renderList) {
  64556. newTexture.renderList = this.renderList.slice(0);
  64557. }
  64558. return newTexture;
  64559. };
  64560. MirrorTexture.prototype.serialize = function () {
  64561. if (!this.name) {
  64562. return null;
  64563. }
  64564. var serializationObject = _super.prototype.serialize.call(this);
  64565. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64566. return serializationObject;
  64567. };
  64568. MirrorTexture.prototype.dispose = function () {
  64569. _super.prototype.dispose.call(this);
  64570. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64571. };
  64572. return MirrorTexture;
  64573. }(BABYLON.RenderTargetTexture));
  64574. BABYLON.MirrorTexture = MirrorTexture;
  64575. })(BABYLON || (BABYLON = {}));
  64576. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64577. var BABYLON;
  64578. (function (BABYLON) {
  64579. /**
  64580. * Creates a refraction texture used by refraction channel of the standard material.
  64581. * @param name the texture name
  64582. * @param size size of the underlying texture
  64583. * @param scene root scene
  64584. */
  64585. var RefractionTexture = /** @class */ (function (_super) {
  64586. __extends(RefractionTexture, _super);
  64587. function RefractionTexture(name, size, scene, generateMipMaps) {
  64588. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64589. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64590. _this.depth = 2.0;
  64591. _this.onBeforeRenderObservable.add(function () {
  64592. scene.clipPlane = _this.refractionPlane;
  64593. });
  64594. _this.onAfterRenderObservable.add(function () {
  64595. delete scene.clipPlane;
  64596. });
  64597. return _this;
  64598. }
  64599. RefractionTexture.prototype.clone = function () {
  64600. var scene = this.getScene();
  64601. if (!scene) {
  64602. return this;
  64603. }
  64604. var textureSize = this.getSize();
  64605. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64606. // Base texture
  64607. newTexture.hasAlpha = this.hasAlpha;
  64608. newTexture.level = this.level;
  64609. // Refraction Texture
  64610. newTexture.refractionPlane = this.refractionPlane.clone();
  64611. if (this.renderList) {
  64612. newTexture.renderList = this.renderList.slice(0);
  64613. }
  64614. newTexture.depth = this.depth;
  64615. return newTexture;
  64616. };
  64617. RefractionTexture.prototype.serialize = function () {
  64618. if (!this.name) {
  64619. return null;
  64620. }
  64621. var serializationObject = _super.prototype.serialize.call(this);
  64622. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64623. serializationObject.depth = this.depth;
  64624. return serializationObject;
  64625. };
  64626. return RefractionTexture;
  64627. }(BABYLON.RenderTargetTexture));
  64628. BABYLON.RefractionTexture = RefractionTexture;
  64629. })(BABYLON || (BABYLON = {}));
  64630. //# sourceMappingURL=babylon.refractionTexture.js.map
  64631. var BABYLON;
  64632. (function (BABYLON) {
  64633. /**
  64634. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64635. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64636. */
  64637. var DynamicTexture = /** @class */ (function (_super) {
  64638. __extends(DynamicTexture, _super);
  64639. /**
  64640. * Creates a {BABYLON.DynamicTexture}
  64641. * @param name defines the name of the texture
  64642. * @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
  64643. * @param scene defines the scene where you want the texture
  64644. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64645. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64646. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64647. */
  64648. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64649. if (scene === void 0) { scene = null; }
  64650. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64651. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64652. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64653. _this.name = name;
  64654. _this._engine = _this.getScene().getEngine();
  64655. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64656. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64657. _this._generateMipMaps = generateMipMaps;
  64658. if (options.getContext) {
  64659. _this._canvas = options;
  64660. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64661. }
  64662. else {
  64663. _this._canvas = document.createElement("canvas");
  64664. if (options.width || options.width === 0) {
  64665. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64666. }
  64667. else {
  64668. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64669. }
  64670. }
  64671. var textureSize = _this.getSize();
  64672. _this._canvas.width = textureSize.width;
  64673. _this._canvas.height = textureSize.height;
  64674. _this._context = _this._canvas.getContext("2d");
  64675. return _this;
  64676. }
  64677. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64678. /**
  64679. * Gets the current state of canRescale
  64680. */
  64681. get: function () {
  64682. return true;
  64683. },
  64684. enumerable: true,
  64685. configurable: true
  64686. });
  64687. DynamicTexture.prototype._recreate = function (textureSize) {
  64688. this._canvas.width = textureSize.width;
  64689. this._canvas.height = textureSize.height;
  64690. this.releaseInternalTexture();
  64691. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64692. };
  64693. /**
  64694. * Scales the texture
  64695. * @param ratio the scale factor to apply to both width and height
  64696. */
  64697. DynamicTexture.prototype.scale = function (ratio) {
  64698. var textureSize = this.getSize();
  64699. textureSize.width *= ratio;
  64700. textureSize.height *= ratio;
  64701. this._recreate(textureSize);
  64702. };
  64703. /**
  64704. * Resizes the texture
  64705. * @param width the new width
  64706. * @param height the new height
  64707. */
  64708. DynamicTexture.prototype.scaleTo = function (width, height) {
  64709. var textureSize = this.getSize();
  64710. textureSize.width = width;
  64711. textureSize.height = height;
  64712. this._recreate(textureSize);
  64713. };
  64714. /**
  64715. * Gets the context of the canvas used by the texture
  64716. * @returns the canvas context of the dynamic texture
  64717. */
  64718. DynamicTexture.prototype.getContext = function () {
  64719. return this._context;
  64720. };
  64721. /**
  64722. * Clears the texture
  64723. */
  64724. DynamicTexture.prototype.clear = function () {
  64725. var size = this.getSize();
  64726. this._context.fillRect(0, 0, size.width, size.height);
  64727. };
  64728. /**
  64729. * Updates the texture
  64730. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64731. * @param premulAlpha defines if alpha is stored as premultiplied
  64732. */
  64733. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64734. if (premulAlpha === void 0) { premulAlpha = false; }
  64735. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64736. };
  64737. /**
  64738. * Draws text onto the texture
  64739. * @param text defines the text to be drawn
  64740. * @param x defines the placement of the text from the left
  64741. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64742. * @param font defines the font to be used with font-style, font-size, font-name
  64743. * @param color defines the color used for the text
  64744. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64745. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64746. * @param update defines whether texture is immediately update (default is true)
  64747. */
  64748. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64749. if (update === void 0) { update = true; }
  64750. var size = this.getSize();
  64751. if (clearColor) {
  64752. this._context.fillStyle = clearColor;
  64753. this._context.fillRect(0, 0, size.width, size.height);
  64754. }
  64755. this._context.font = font;
  64756. if (x === null || x === undefined) {
  64757. var textSize = this._context.measureText(text);
  64758. x = (size.width - textSize.width) / 2;
  64759. }
  64760. if (y === null || y === undefined) {
  64761. var fontSize = parseInt((font.replace(/\D/g, '')));
  64762. y = (size.height / 2) + (fontSize / 3.65);
  64763. }
  64764. this._context.fillStyle = color;
  64765. this._context.fillText(text, x, y);
  64766. if (update) {
  64767. this.update(invertY);
  64768. }
  64769. };
  64770. /**
  64771. * Clones the texture
  64772. * @returns the clone of the texture.
  64773. */
  64774. DynamicTexture.prototype.clone = function () {
  64775. var scene = this.getScene();
  64776. if (!scene) {
  64777. return this;
  64778. }
  64779. var textureSize = this.getSize();
  64780. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64781. // Base texture
  64782. newTexture.hasAlpha = this.hasAlpha;
  64783. newTexture.level = this.level;
  64784. // Dynamic Texture
  64785. newTexture.wrapU = this.wrapU;
  64786. newTexture.wrapV = this.wrapV;
  64787. return newTexture;
  64788. };
  64789. /** @hidden */
  64790. DynamicTexture.prototype._rebuild = function () {
  64791. this.update();
  64792. };
  64793. return DynamicTexture;
  64794. }(BABYLON.Texture));
  64795. BABYLON.DynamicTexture = DynamicTexture;
  64796. })(BABYLON || (BABYLON = {}));
  64797. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64798. var BABYLON;
  64799. (function (BABYLON) {
  64800. var VideoTexture = /** @class */ (function (_super) {
  64801. __extends(VideoTexture, _super);
  64802. /**
  64803. * Creates a video texture.
  64804. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64805. * @param {string | null} name optional name, will detect from video source, if not defined
  64806. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64807. * @param {BABYLON.Scene} scene is obviously the current scene.
  64808. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64809. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64810. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64811. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64812. */
  64813. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64814. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64815. if (invertY === void 0) { invertY = false; }
  64816. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64817. if (settings === void 0) { settings = {
  64818. autoPlay: true,
  64819. loop: true,
  64820. autoUpdateTexture: true,
  64821. }; }
  64822. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64823. _this._stillImageCaptured = false;
  64824. _this._createInternalTexture = function () {
  64825. if (_this._texture != null) {
  64826. return;
  64827. }
  64828. if (!_this._engine.needPOTTextures ||
  64829. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64830. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64831. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64832. }
  64833. else {
  64834. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64835. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64836. _this._generateMipMaps = false;
  64837. }
  64838. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64839. if (!_this.video.autoplay) {
  64840. var oldHandler_1 = _this.video.onplaying;
  64841. _this.video.onplaying = function () {
  64842. _this.video.onplaying = oldHandler_1;
  64843. _this._texture.isReady = true;
  64844. _this._updateInternalTexture();
  64845. _this.video.pause();
  64846. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64847. _this.onLoadObservable.notifyObservers(_this);
  64848. }
  64849. };
  64850. _this.video.play();
  64851. }
  64852. else {
  64853. _this._texture.isReady = true;
  64854. _this._updateInternalTexture();
  64855. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64856. _this.onLoadObservable.notifyObservers(_this);
  64857. }
  64858. }
  64859. };
  64860. _this.reset = function () {
  64861. if (_this._texture == null) {
  64862. return;
  64863. }
  64864. _this._texture.dispose();
  64865. _this._texture = null;
  64866. };
  64867. _this._updateInternalTexture = function (e) {
  64868. if (_this._texture == null || !_this._texture.isReady) {
  64869. return;
  64870. }
  64871. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64872. return;
  64873. }
  64874. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64875. };
  64876. _this._engine = _this.getScene().getEngine();
  64877. _this._generateMipMaps = generateMipMaps;
  64878. _this._samplingMode = samplingMode;
  64879. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64880. _this.name = name || _this._getName(src);
  64881. _this.video = _this._getVideo(src);
  64882. if (settings.autoPlay !== undefined) {
  64883. _this.video.autoplay = settings.autoPlay;
  64884. }
  64885. if (settings.loop !== undefined) {
  64886. _this.video.loop = settings.loop;
  64887. }
  64888. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64889. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64890. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64891. _this.video.addEventListener("emptied", _this.reset);
  64892. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64893. _this._createInternalTexture();
  64894. }
  64895. return _this;
  64896. }
  64897. VideoTexture.prototype._getName = function (src) {
  64898. if (src instanceof HTMLVideoElement) {
  64899. return src.currentSrc;
  64900. }
  64901. if (typeof src === "object") {
  64902. return src.toString();
  64903. }
  64904. return src;
  64905. };
  64906. ;
  64907. VideoTexture.prototype._getVideo = function (src) {
  64908. if (src instanceof HTMLVideoElement) {
  64909. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64910. return src;
  64911. }
  64912. var video = document.createElement("video");
  64913. if (typeof src === "string") {
  64914. BABYLON.Tools.SetCorsBehavior(src, video);
  64915. video.src = src;
  64916. }
  64917. else {
  64918. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64919. src.forEach(function (url) {
  64920. var source = document.createElement("source");
  64921. source.src = url;
  64922. video.appendChild(source);
  64923. });
  64924. }
  64925. return video;
  64926. };
  64927. ;
  64928. /**
  64929. * Internal method to initiate `update`.
  64930. */
  64931. VideoTexture.prototype._rebuild = function () {
  64932. this.update();
  64933. };
  64934. /**
  64935. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64936. */
  64937. VideoTexture.prototype.update = function () {
  64938. if (!this.autoUpdateTexture) {
  64939. // Expecting user to call `updateTexture` manually
  64940. return;
  64941. }
  64942. this.updateTexture(true);
  64943. };
  64944. /**
  64945. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64946. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64947. */
  64948. VideoTexture.prototype.updateTexture = function (isVisible) {
  64949. if (!isVisible) {
  64950. return;
  64951. }
  64952. if (this.video.paused && this._stillImageCaptured) {
  64953. return;
  64954. }
  64955. this._stillImageCaptured = true;
  64956. this._updateInternalTexture();
  64957. };
  64958. /**
  64959. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64960. * @param url New url.
  64961. */
  64962. VideoTexture.prototype.updateURL = function (url) {
  64963. this.video.src = url;
  64964. };
  64965. VideoTexture.prototype.dispose = function () {
  64966. _super.prototype.dispose.call(this);
  64967. this.video.removeEventListener("canplay", this._createInternalTexture);
  64968. this.video.removeEventListener("paused", this._updateInternalTexture);
  64969. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64970. this.video.removeEventListener("emptied", this.reset);
  64971. this.video.pause();
  64972. };
  64973. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64974. var video = document.createElement("video");
  64975. var constraintsDeviceId;
  64976. if (constraints && constraints.deviceId) {
  64977. constraintsDeviceId = {
  64978. exact: constraints.deviceId,
  64979. };
  64980. }
  64981. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64982. if (navigator.mediaDevices) {
  64983. navigator.mediaDevices.getUserMedia({ video: constraints })
  64984. .then(function (stream) {
  64985. if (video.mozSrcObject !== undefined) {
  64986. // hack for Firefox < 19
  64987. video.mozSrcObject = stream;
  64988. }
  64989. else {
  64990. video.srcObject = stream;
  64991. }
  64992. var onPlaying = function () {
  64993. if (onReady) {
  64994. onReady(new VideoTexture("video", video, scene, true, true));
  64995. }
  64996. video.removeEventListener("playing", onPlaying);
  64997. };
  64998. video.addEventListener("playing", onPlaying);
  64999. video.play();
  65000. })
  65001. .catch(function (err) {
  65002. BABYLON.Tools.Error(err.name);
  65003. });
  65004. }
  65005. else {
  65006. navigator.getUserMedia =
  65007. navigator.getUserMedia ||
  65008. navigator.webkitGetUserMedia ||
  65009. navigator.mozGetUserMedia ||
  65010. navigator.msGetUserMedia;
  65011. if (navigator.getUserMedia) {
  65012. navigator.getUserMedia({
  65013. video: {
  65014. deviceId: constraintsDeviceId,
  65015. width: {
  65016. min: (constraints && constraints.minWidth) || 256,
  65017. max: (constraints && constraints.maxWidth) || 640,
  65018. },
  65019. height: {
  65020. min: (constraints && constraints.minHeight) || 256,
  65021. max: (constraints && constraints.maxHeight) || 480,
  65022. },
  65023. },
  65024. }, function (stream) {
  65025. if (video.mozSrcObject !== undefined) {
  65026. // hack for Firefox < 19
  65027. video.mozSrcObject = stream;
  65028. }
  65029. else {
  65030. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65031. }
  65032. video.play();
  65033. if (onReady) {
  65034. onReady(new VideoTexture("video", video, scene, true, true));
  65035. }
  65036. }, function (e) {
  65037. BABYLON.Tools.Error(e.name);
  65038. });
  65039. }
  65040. }
  65041. };
  65042. return VideoTexture;
  65043. }(BABYLON.Texture));
  65044. BABYLON.VideoTexture = VideoTexture;
  65045. })(BABYLON || (BABYLON = {}));
  65046. //# sourceMappingURL=babylon.videoTexture.js.map
  65047. var BABYLON;
  65048. (function (BABYLON) {
  65049. var RawTexture = /** @class */ (function (_super) {
  65050. __extends(RawTexture, _super);
  65051. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65052. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65053. if (invertY === void 0) { invertY = false; }
  65054. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65055. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65056. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65057. _this.format = format;
  65058. _this._engine = scene.getEngine();
  65059. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65060. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65061. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65062. return _this;
  65063. }
  65064. RawTexture.prototype.update = function (data) {
  65065. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65066. };
  65067. // Statics
  65068. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65069. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65070. if (invertY === void 0) { invertY = false; }
  65071. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65072. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65073. };
  65074. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65075. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65076. if (invertY === void 0) { invertY = false; }
  65077. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65078. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65079. };
  65080. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65081. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65082. if (invertY === void 0) { invertY = false; }
  65083. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65084. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65085. };
  65086. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65087. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65088. if (invertY === void 0) { invertY = false; }
  65089. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65090. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65091. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65092. };
  65093. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65094. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65095. if (invertY === void 0) { invertY = false; }
  65096. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65097. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65098. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65099. };
  65100. return RawTexture;
  65101. }(BABYLON.Texture));
  65102. BABYLON.RawTexture = RawTexture;
  65103. })(BABYLON || (BABYLON = {}));
  65104. //# sourceMappingURL=babylon.rawTexture.js.map
  65105. var BABYLON;
  65106. (function (BABYLON) {
  65107. /**
  65108. * Class used to store 3D textures containing user data
  65109. */
  65110. var RawTexture3D = /** @class */ (function (_super) {
  65111. __extends(RawTexture3D, _super);
  65112. /**
  65113. * Create a new RawTexture3D
  65114. * @param data defines the data of the texture
  65115. * @param width defines the width of the texture
  65116. * @param height defines the height of the texture
  65117. * @param depth defines the depth of the texture
  65118. * @param format defines the texture format to use
  65119. * @param scene defines the hosting scene
  65120. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65121. * @param invertY defines if texture must be stored with Y axis inverted
  65122. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65123. */
  65124. function RawTexture3D(data, width, height, depth,
  65125. /** Gets or sets the texture format to use*/
  65126. format, scene, generateMipMaps, invertY, samplingMode) {
  65127. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65128. if (invertY === void 0) { invertY = false; }
  65129. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65130. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65131. _this.format = format;
  65132. _this._engine = scene.getEngine();
  65133. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  65134. _this.is3D = true;
  65135. return _this;
  65136. }
  65137. /**
  65138. * Update the texture with new data
  65139. * @param data defines the data to store in the texture
  65140. */
  65141. RawTexture3D.prototype.update = function (data) {
  65142. if (!this._texture) {
  65143. return;
  65144. }
  65145. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  65146. };
  65147. return RawTexture3D;
  65148. }(BABYLON.Texture));
  65149. BABYLON.RawTexture3D = RawTexture3D;
  65150. })(BABYLON || (BABYLON = {}));
  65151. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65152. var BABYLON;
  65153. (function (BABYLON) {
  65154. /**
  65155. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65156. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65157. */
  65158. var PostProcess = /** @class */ (function () {
  65159. /**
  65160. * Creates a new instance PostProcess
  65161. * @param name The name of the PostProcess.
  65162. * @param fragmentUrl The url of the fragment shader to be used.
  65163. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65164. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65165. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65166. * @param camera The camera to apply the render pass to.
  65167. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65168. * @param engine The engine which the post process will be applied. (default: current engine)
  65169. * @param reusable If the post process can be reused on the same frame. (default: false)
  65170. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65171. * @param textureType Type of textures used when performing the post process. (default: 0)
  65172. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65173. * @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
  65174. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65175. */
  65176. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65177. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65178. if (defines === void 0) { defines = null; }
  65179. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65180. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65181. if (blockCompilation === void 0) { blockCompilation = false; }
  65182. this.name = name;
  65183. /**
  65184. * Width of the texture to apply the post process on
  65185. */
  65186. this.width = -1;
  65187. /**
  65188. * Height of the texture to apply the post process on
  65189. */
  65190. this.height = -1;
  65191. /**
  65192. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65193. */
  65194. this._outputTexture = null;
  65195. /**
  65196. * If the buffer needs to be cleared before applying the post process. (default: true)
  65197. * Should be set to false if shader will overwrite all previous pixels.
  65198. */
  65199. this.autoClear = true;
  65200. /**
  65201. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65202. */
  65203. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65204. /**
  65205. * Animations to be used for the post processing
  65206. */
  65207. this.animations = new Array();
  65208. /**
  65209. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65210. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65211. */
  65212. this.enablePixelPerfectMode = false;
  65213. /**
  65214. * Force the postprocess to be applied without taking in account viewport
  65215. */
  65216. this.forceFullscreenViewport = true;
  65217. /**
  65218. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65219. */
  65220. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65221. /**
  65222. * Force textures to be a power of two (default: false)
  65223. */
  65224. this.alwaysForcePOT = false;
  65225. /**
  65226. * Number of sample textures (default: 1)
  65227. */
  65228. this.samples = 1;
  65229. /**
  65230. * Modify the scale of the post process to be the same as the viewport (default: false)
  65231. */
  65232. this.adaptScaleToCurrentViewport = false;
  65233. this._reusable = false;
  65234. /**
  65235. * Smart array of input and output textures for the post process.
  65236. */
  65237. this._textures = new BABYLON.SmartArray(2);
  65238. /**
  65239. * The index in _textures that corresponds to the output texture.
  65240. */
  65241. this._currentRenderTextureInd = 0;
  65242. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65243. this._texelSize = BABYLON.Vector2.Zero();
  65244. // Events
  65245. /**
  65246. * An event triggered when the postprocess is activated.
  65247. */
  65248. this.onActivateObservable = new BABYLON.Observable();
  65249. /**
  65250. * An event triggered when the postprocess changes its size.
  65251. */
  65252. this.onSizeChangedObservable = new BABYLON.Observable();
  65253. /**
  65254. * An event triggered when the postprocess applies its effect.
  65255. */
  65256. this.onApplyObservable = new BABYLON.Observable();
  65257. /**
  65258. * An event triggered before rendering the postprocess
  65259. */
  65260. this.onBeforeRenderObservable = new BABYLON.Observable();
  65261. /**
  65262. * An event triggered after rendering the postprocess
  65263. */
  65264. this.onAfterRenderObservable = new BABYLON.Observable();
  65265. if (camera != null) {
  65266. this._camera = camera;
  65267. this._scene = camera.getScene();
  65268. camera.attachPostProcess(this);
  65269. this._engine = this._scene.getEngine();
  65270. this._scene.postProcesses.push(this);
  65271. }
  65272. else if (engine) {
  65273. this._engine = engine;
  65274. this._engine.postProcesses.push(this);
  65275. }
  65276. this._options = options;
  65277. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65278. this._reusable = reusable || false;
  65279. this._textureType = textureType;
  65280. this._samplers = samplers || [];
  65281. this._samplers.push("textureSampler");
  65282. this._fragmentUrl = fragmentUrl;
  65283. this._vertexUrl = vertexUrl;
  65284. this._parameters = parameters || [];
  65285. this._parameters.push("scale");
  65286. this._indexParameters = indexParameters;
  65287. if (!blockCompilation) {
  65288. this.updateEffect(defines);
  65289. }
  65290. }
  65291. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65292. /**
  65293. * A function that is added to the onActivateObservable
  65294. */
  65295. set: function (callback) {
  65296. if (this._onActivateObserver) {
  65297. this.onActivateObservable.remove(this._onActivateObserver);
  65298. }
  65299. if (callback) {
  65300. this._onActivateObserver = this.onActivateObservable.add(callback);
  65301. }
  65302. },
  65303. enumerable: true,
  65304. configurable: true
  65305. });
  65306. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65307. /**
  65308. * A function that is added to the onSizeChangedObservable
  65309. */
  65310. set: function (callback) {
  65311. if (this._onSizeChangedObserver) {
  65312. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65313. }
  65314. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65315. },
  65316. enumerable: true,
  65317. configurable: true
  65318. });
  65319. Object.defineProperty(PostProcess.prototype, "onApply", {
  65320. /**
  65321. * A function that is added to the onApplyObservable
  65322. */
  65323. set: function (callback) {
  65324. if (this._onApplyObserver) {
  65325. this.onApplyObservable.remove(this._onApplyObserver);
  65326. }
  65327. this._onApplyObserver = this.onApplyObservable.add(callback);
  65328. },
  65329. enumerable: true,
  65330. configurable: true
  65331. });
  65332. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65333. /**
  65334. * A function that is added to the onBeforeRenderObservable
  65335. */
  65336. set: function (callback) {
  65337. if (this._onBeforeRenderObserver) {
  65338. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65339. }
  65340. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65341. },
  65342. enumerable: true,
  65343. configurable: true
  65344. });
  65345. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65346. /**
  65347. * A function that is added to the onAfterRenderObservable
  65348. */
  65349. set: function (callback) {
  65350. if (this._onAfterRenderObserver) {
  65351. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65352. }
  65353. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65354. },
  65355. enumerable: true,
  65356. configurable: true
  65357. });
  65358. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65359. /**
  65360. * 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
  65361. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65362. */
  65363. get: function () {
  65364. return this._textures.data[this._currentRenderTextureInd];
  65365. },
  65366. set: function (value) {
  65367. this._forcedOutputTexture = value;
  65368. },
  65369. enumerable: true,
  65370. configurable: true
  65371. });
  65372. /**
  65373. * Gets the camera which post process is applied to.
  65374. * @returns The camera the post process is applied to.
  65375. */
  65376. PostProcess.prototype.getCamera = function () {
  65377. return this._camera;
  65378. };
  65379. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65380. /**
  65381. * Gets the texel size of the postprocess.
  65382. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65383. */
  65384. get: function () {
  65385. if (this._shareOutputWithPostProcess) {
  65386. return this._shareOutputWithPostProcess.texelSize;
  65387. }
  65388. if (this._forcedOutputTexture) {
  65389. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65390. }
  65391. return this._texelSize;
  65392. },
  65393. enumerable: true,
  65394. configurable: true
  65395. });
  65396. /**
  65397. * Gets the engine which this post process belongs to.
  65398. * @returns The engine the post process was enabled with.
  65399. */
  65400. PostProcess.prototype.getEngine = function () {
  65401. return this._engine;
  65402. };
  65403. /**
  65404. * The effect that is created when initializing the post process.
  65405. * @returns The created effect corrisponding the the postprocess.
  65406. */
  65407. PostProcess.prototype.getEffect = function () {
  65408. return this._effect;
  65409. };
  65410. /**
  65411. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65412. * @param postProcess The post process to share the output with.
  65413. * @returns This post process.
  65414. */
  65415. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65416. this._disposeTextures();
  65417. this._shareOutputWithPostProcess = postProcess;
  65418. return this;
  65419. };
  65420. /**
  65421. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65422. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65423. */
  65424. PostProcess.prototype.useOwnOutput = function () {
  65425. if (this._textures.length == 0) {
  65426. this._textures = new BABYLON.SmartArray(2);
  65427. }
  65428. this._shareOutputWithPostProcess = null;
  65429. };
  65430. /**
  65431. * Updates the effect with the current post process compile time values and recompiles the shader.
  65432. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65433. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65434. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65435. * @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
  65436. * @param onCompiled Called when the shader has been compiled.
  65437. * @param onError Called if there is an error when compiling a shader.
  65438. */
  65439. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65440. if (defines === void 0) { defines = null; }
  65441. if (uniforms === void 0) { uniforms = null; }
  65442. if (samplers === void 0) { samplers = null; }
  65443. 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);
  65444. };
  65445. /**
  65446. * The post process is reusable if it can be used multiple times within one frame.
  65447. * @returns If the post process is reusable
  65448. */
  65449. PostProcess.prototype.isReusable = function () {
  65450. return this._reusable;
  65451. };
  65452. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65453. PostProcess.prototype.markTextureDirty = function () {
  65454. this.width = -1;
  65455. };
  65456. /**
  65457. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65458. * 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.
  65459. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65460. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65461. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65462. * @returns The target texture that was bound to be written to.
  65463. */
  65464. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65465. var _this = this;
  65466. if (sourceTexture === void 0) { sourceTexture = null; }
  65467. camera = camera || this._camera;
  65468. var scene = camera.getScene();
  65469. var engine = scene.getEngine();
  65470. var maxSize = engine.getCaps().maxTextureSize;
  65471. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65472. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65473. // 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
  65474. var webVRCamera = camera.parent;
  65475. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65476. requiredWidth /= 2;
  65477. }
  65478. var desiredWidth = (this._options.width || requiredWidth);
  65479. var desiredHeight = this._options.height || requiredHeight;
  65480. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65481. if (this.adaptScaleToCurrentViewport) {
  65482. var currentViewport = engine.currentViewport;
  65483. if (currentViewport) {
  65484. desiredWidth *= currentViewport.width;
  65485. desiredHeight *= currentViewport.height;
  65486. }
  65487. }
  65488. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65489. if (!this._options.width) {
  65490. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65491. }
  65492. if (!this._options.height) {
  65493. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65494. }
  65495. }
  65496. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65497. if (this._textures.length > 0) {
  65498. for (var i = 0; i < this._textures.length; i++) {
  65499. this._engine._releaseTexture(this._textures.data[i]);
  65500. }
  65501. this._textures.reset();
  65502. }
  65503. this.width = desiredWidth;
  65504. this.height = desiredHeight;
  65505. var textureSize = { width: this.width, height: this.height };
  65506. var textureOptions = {
  65507. generateMipMaps: false,
  65508. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65509. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65510. samplingMode: this.renderTargetSamplingMode,
  65511. type: this._textureType
  65512. };
  65513. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65514. if (this._reusable) {
  65515. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65516. }
  65517. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65518. this.onSizeChangedObservable.notifyObservers(this);
  65519. }
  65520. this._textures.forEach(function (texture) {
  65521. if (texture.samples !== _this.samples) {
  65522. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65523. }
  65524. });
  65525. }
  65526. var target;
  65527. if (this._shareOutputWithPostProcess) {
  65528. target = this._shareOutputWithPostProcess.inputTexture;
  65529. }
  65530. else if (this._forcedOutputTexture) {
  65531. target = this._forcedOutputTexture;
  65532. this.width = this._forcedOutputTexture.width;
  65533. this.height = this._forcedOutputTexture.height;
  65534. }
  65535. else {
  65536. target = this.inputTexture;
  65537. }
  65538. // Bind the input of this post process to be used as the output of the previous post process.
  65539. if (this.enablePixelPerfectMode) {
  65540. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65541. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65542. }
  65543. else {
  65544. this._scaleRatio.copyFromFloats(1, 1);
  65545. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65546. }
  65547. this.onActivateObservable.notifyObservers(camera);
  65548. // Clear
  65549. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65550. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65551. }
  65552. if (this._reusable) {
  65553. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65554. }
  65555. return target;
  65556. };
  65557. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65558. /**
  65559. * If the post process is supported.
  65560. */
  65561. get: function () {
  65562. return this._effect.isSupported;
  65563. },
  65564. enumerable: true,
  65565. configurable: true
  65566. });
  65567. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65568. /**
  65569. * The aspect ratio of the output texture.
  65570. */
  65571. get: function () {
  65572. if (this._shareOutputWithPostProcess) {
  65573. return this._shareOutputWithPostProcess.aspectRatio;
  65574. }
  65575. if (this._forcedOutputTexture) {
  65576. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65577. }
  65578. return this.width / this.height;
  65579. },
  65580. enumerable: true,
  65581. configurable: true
  65582. });
  65583. /**
  65584. * Get a value indicating if the post-process is ready to be used
  65585. * @returns true if the post-process is ready (shader is compiled)
  65586. */
  65587. PostProcess.prototype.isReady = function () {
  65588. return this._effect && this._effect.isReady();
  65589. };
  65590. /**
  65591. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65592. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65593. */
  65594. PostProcess.prototype.apply = function () {
  65595. // Check
  65596. if (!this._effect || !this._effect.isReady())
  65597. return null;
  65598. // States
  65599. this._engine.enableEffect(this._effect);
  65600. this._engine.setState(false);
  65601. this._engine.setDepthBuffer(false);
  65602. this._engine.setDepthWrite(false);
  65603. // Alpha
  65604. this._engine.setAlphaMode(this.alphaMode);
  65605. if (this.alphaConstants) {
  65606. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65607. }
  65608. // Bind the output texture of the preivous post process as the input to this post process.
  65609. var source;
  65610. if (this._shareOutputWithPostProcess) {
  65611. source = this._shareOutputWithPostProcess.inputTexture;
  65612. }
  65613. else if (this._forcedOutputTexture) {
  65614. source = this._forcedOutputTexture;
  65615. }
  65616. else {
  65617. source = this.inputTexture;
  65618. }
  65619. this._effect._bindTexture("textureSampler", source);
  65620. // Parameters
  65621. this._effect.setVector2("scale", this._scaleRatio);
  65622. this.onApplyObservable.notifyObservers(this._effect);
  65623. return this._effect;
  65624. };
  65625. PostProcess.prototype._disposeTextures = function () {
  65626. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65627. return;
  65628. }
  65629. if (this._textures.length > 0) {
  65630. for (var i = 0; i < this._textures.length; i++) {
  65631. this._engine._releaseTexture(this._textures.data[i]);
  65632. }
  65633. }
  65634. this._textures.dispose();
  65635. };
  65636. /**
  65637. * Disposes the post process.
  65638. * @param camera The camera to dispose the post process on.
  65639. */
  65640. PostProcess.prototype.dispose = function (camera) {
  65641. camera = camera || this._camera;
  65642. this._disposeTextures();
  65643. if (this._scene) {
  65644. var index_1 = this._scene.postProcesses.indexOf(this);
  65645. if (index_1 !== -1) {
  65646. this._scene.postProcesses.splice(index_1, 1);
  65647. }
  65648. }
  65649. else {
  65650. var index_2 = this._engine.postProcesses.indexOf(this);
  65651. if (index_2 !== -1) {
  65652. this._engine.postProcesses.splice(index_2, 1);
  65653. }
  65654. }
  65655. if (!camera) {
  65656. return;
  65657. }
  65658. camera.detachPostProcess(this);
  65659. var index = camera._postProcesses.indexOf(this);
  65660. if (index === 0 && camera._postProcesses.length > 0) {
  65661. var firstPostProcess = this._camera._getFirstPostProcess();
  65662. if (firstPostProcess) {
  65663. firstPostProcess.markTextureDirty();
  65664. }
  65665. }
  65666. this.onActivateObservable.clear();
  65667. this.onAfterRenderObservable.clear();
  65668. this.onApplyObservable.clear();
  65669. this.onBeforeRenderObservable.clear();
  65670. this.onSizeChangedObservable.clear();
  65671. };
  65672. return PostProcess;
  65673. }());
  65674. BABYLON.PostProcess = PostProcess;
  65675. })(BABYLON || (BABYLON = {}));
  65676. //# sourceMappingURL=babylon.postProcess.js.map
  65677. var BABYLON;
  65678. (function (BABYLON) {
  65679. var PassPostProcess = /** @class */ (function (_super) {
  65680. __extends(PassPostProcess, _super);
  65681. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65682. if (camera === void 0) { camera = null; }
  65683. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65684. if (blockCompilation === void 0) { blockCompilation = false; }
  65685. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65686. }
  65687. return PassPostProcess;
  65688. }(BABYLON.PostProcess));
  65689. BABYLON.PassPostProcess = PassPostProcess;
  65690. })(BABYLON || (BABYLON = {}));
  65691. //# sourceMappingURL=babylon.passPostProcess.js.map
  65692. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65693. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65694. s = arguments[i];
  65695. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65696. t[p] = s[p];
  65697. }
  65698. return t;
  65699. };
  65700. var BABYLON;
  65701. (function (BABYLON) {
  65702. /**
  65703. * Default implementation IShadowGenerator.
  65704. * This is the main object responsible of generating shadows in the framework.
  65705. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65706. */
  65707. var ShadowGenerator = /** @class */ (function () {
  65708. /**
  65709. * Creates a ShadowGenerator object.
  65710. * A ShadowGenerator is the required tool to use the shadows.
  65711. * Each light casting shadows needs to use its own ShadowGenerator.
  65712. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65713. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65714. * @param light The light object generating the shadows.
  65715. * @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.
  65716. */
  65717. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65718. this._bias = 0.00005;
  65719. this._normalBias = 0;
  65720. this._blurBoxOffset = 1;
  65721. this._blurScale = 2;
  65722. this._blurKernel = 1;
  65723. this._useKernelBlur = false;
  65724. this._filter = ShadowGenerator.FILTER_NONE;
  65725. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65726. this._contactHardeningLightSizeUVRatio = 0.1;
  65727. this._darkness = 0;
  65728. this._transparencyShadow = false;
  65729. /**
  65730. * Controls the extent to which the shadows fade out at the edge of the frustum
  65731. * Used only by directionals and spots
  65732. */
  65733. this.frustumEdgeFalloff = 0;
  65734. /**
  65735. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65736. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65737. * It might on the other hand introduce peter panning.
  65738. */
  65739. this.forceBackFacesOnly = false;
  65740. this._lightDirection = BABYLON.Vector3.Zero();
  65741. this._viewMatrix = BABYLON.Matrix.Zero();
  65742. this._projectionMatrix = BABYLON.Matrix.Zero();
  65743. this._transformMatrix = BABYLON.Matrix.Zero();
  65744. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65745. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65746. this._currentFaceIndex = 0;
  65747. this._currentFaceIndexCache = 0;
  65748. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65749. this._mapSize = mapSize;
  65750. this._light = light;
  65751. this._scene = light.getScene();
  65752. light._shadowGenerator = this;
  65753. // Texture type fallback from float to int if not supported.
  65754. var caps = this._scene.getEngine().getCaps();
  65755. if (!useFullFloatFirst) {
  65756. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65757. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65758. }
  65759. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65760. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65761. }
  65762. else {
  65763. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65764. }
  65765. }
  65766. else {
  65767. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65768. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65769. }
  65770. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65771. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65772. }
  65773. else {
  65774. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65775. }
  65776. }
  65777. this._initializeGenerator();
  65778. this._applyFilterValues();
  65779. }
  65780. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65781. /**
  65782. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65783. */
  65784. get: function () {
  65785. return this._bias;
  65786. },
  65787. /**
  65788. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65789. */
  65790. set: function (bias) {
  65791. this._bias = bias;
  65792. },
  65793. enumerable: true,
  65794. configurable: true
  65795. });
  65796. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65797. /**
  65798. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65799. */
  65800. get: function () {
  65801. return this._normalBias;
  65802. },
  65803. /**
  65804. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65805. */
  65806. set: function (normalBias) {
  65807. this._normalBias = normalBias;
  65808. },
  65809. enumerable: true,
  65810. configurable: true
  65811. });
  65812. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65813. /**
  65814. * Gets the blur box offset: offset applied during the blur pass.
  65815. * Only usefull if useKernelBlur = false
  65816. */
  65817. get: function () {
  65818. return this._blurBoxOffset;
  65819. },
  65820. /**
  65821. * Sets the blur box offset: offset applied during the blur pass.
  65822. * Only usefull if useKernelBlur = false
  65823. */
  65824. set: function (value) {
  65825. if (this._blurBoxOffset === value) {
  65826. return;
  65827. }
  65828. this._blurBoxOffset = value;
  65829. this._disposeBlurPostProcesses();
  65830. },
  65831. enumerable: true,
  65832. configurable: true
  65833. });
  65834. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65835. /**
  65836. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65837. * 2 means half of the size.
  65838. */
  65839. get: function () {
  65840. return this._blurScale;
  65841. },
  65842. /**
  65843. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65844. * 2 means half of the size.
  65845. */
  65846. set: function (value) {
  65847. if (this._blurScale === value) {
  65848. return;
  65849. }
  65850. this._blurScale = value;
  65851. this._disposeBlurPostProcesses();
  65852. },
  65853. enumerable: true,
  65854. configurable: true
  65855. });
  65856. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65857. /**
  65858. * Gets the blur kernel: kernel size of the blur pass.
  65859. * Only usefull if useKernelBlur = true
  65860. */
  65861. get: function () {
  65862. return this._blurKernel;
  65863. },
  65864. /**
  65865. * Sets the blur kernel: kernel size of the blur pass.
  65866. * Only usefull if useKernelBlur = true
  65867. */
  65868. set: function (value) {
  65869. if (this._blurKernel === value) {
  65870. return;
  65871. }
  65872. this._blurKernel = value;
  65873. this._disposeBlurPostProcesses();
  65874. },
  65875. enumerable: true,
  65876. configurable: true
  65877. });
  65878. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65879. /**
  65880. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65881. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65882. */
  65883. get: function () {
  65884. return this._useKernelBlur;
  65885. },
  65886. /**
  65887. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65888. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65889. */
  65890. set: function (value) {
  65891. if (this._useKernelBlur === value) {
  65892. return;
  65893. }
  65894. this._useKernelBlur = value;
  65895. this._disposeBlurPostProcesses();
  65896. },
  65897. enumerable: true,
  65898. configurable: true
  65899. });
  65900. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65901. /**
  65902. * Gets the depth scale used in ESM mode.
  65903. */
  65904. get: function () {
  65905. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65906. },
  65907. /**
  65908. * Sets the depth scale used in ESM mode.
  65909. * This can override the scale stored on the light.
  65910. */
  65911. set: function (value) {
  65912. this._depthScale = value;
  65913. },
  65914. enumerable: true,
  65915. configurable: true
  65916. });
  65917. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65918. /**
  65919. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65920. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65921. */
  65922. get: function () {
  65923. return this._filter;
  65924. },
  65925. /**
  65926. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65927. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65928. */
  65929. set: function (value) {
  65930. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65931. if (this._light.needCube()) {
  65932. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65933. this.useExponentialShadowMap = true;
  65934. return;
  65935. }
  65936. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65937. this.useCloseExponentialShadowMap = true;
  65938. return;
  65939. }
  65940. // PCF on cubemap would also be expensive
  65941. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65942. this.usePoissonSampling = true;
  65943. return;
  65944. }
  65945. }
  65946. // Weblg1 fallback for PCF.
  65947. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65948. if (this._scene.getEngine().webGLVersion === 1) {
  65949. this.usePoissonSampling = true;
  65950. return;
  65951. }
  65952. }
  65953. if (this._filter === value) {
  65954. return;
  65955. }
  65956. this._filter = value;
  65957. this._disposeBlurPostProcesses();
  65958. this._applyFilterValues();
  65959. this._light._markMeshesAsLightDirty();
  65960. },
  65961. enumerable: true,
  65962. configurable: true
  65963. });
  65964. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65965. /**
  65966. * Gets if the current filter is set to Poisson Sampling.
  65967. */
  65968. get: function () {
  65969. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65970. },
  65971. /**
  65972. * Sets the current filter to Poisson Sampling.
  65973. */
  65974. set: function (value) {
  65975. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65976. return;
  65977. }
  65978. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65979. },
  65980. enumerable: true,
  65981. configurable: true
  65982. });
  65983. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65984. /**
  65985. * Gets if the current filter is set to VSM.
  65986. * DEPRECATED. Should use useExponentialShadowMap instead.
  65987. */
  65988. get: function () {
  65989. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65990. return this.useExponentialShadowMap;
  65991. },
  65992. /**
  65993. * Sets the current filter is to VSM.
  65994. * DEPRECATED. Should use useExponentialShadowMap instead.
  65995. */
  65996. set: function (value) {
  65997. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65998. this.useExponentialShadowMap = value;
  65999. },
  66000. enumerable: true,
  66001. configurable: true
  66002. });
  66003. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66004. /**
  66005. * Gets if the current filter is set to blurred VSM.
  66006. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66007. */
  66008. get: function () {
  66009. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66010. return this.useBlurExponentialShadowMap;
  66011. },
  66012. /**
  66013. * Sets the current filter is to blurred VSM.
  66014. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66015. */
  66016. set: function (value) {
  66017. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66018. this.useBlurExponentialShadowMap = value;
  66019. },
  66020. enumerable: true,
  66021. configurable: true
  66022. });
  66023. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66024. /**
  66025. * Gets if the current filter is set to ESM.
  66026. */
  66027. get: function () {
  66028. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66029. },
  66030. /**
  66031. * Sets the current filter is to ESM.
  66032. */
  66033. set: function (value) {
  66034. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66035. return;
  66036. }
  66037. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66038. },
  66039. enumerable: true,
  66040. configurable: true
  66041. });
  66042. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66043. /**
  66044. * Gets if the current filter is set to filtered ESM.
  66045. */
  66046. get: function () {
  66047. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66048. },
  66049. /**
  66050. * Gets if the current filter is set to filtered ESM.
  66051. */
  66052. set: function (value) {
  66053. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66054. return;
  66055. }
  66056. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66057. },
  66058. enumerable: true,
  66059. configurable: true
  66060. });
  66061. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66062. /**
  66063. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66064. * exponential to prevent steep falloff artifacts).
  66065. */
  66066. get: function () {
  66067. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66068. },
  66069. /**
  66070. * Sets the current filter to "close ESM" (using the inverse of the
  66071. * exponential to prevent steep falloff artifacts).
  66072. */
  66073. set: function (value) {
  66074. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66075. return;
  66076. }
  66077. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66078. },
  66079. enumerable: true,
  66080. configurable: true
  66081. });
  66082. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66083. /**
  66084. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66085. * exponential to prevent steep falloff artifacts).
  66086. */
  66087. get: function () {
  66088. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66089. },
  66090. /**
  66091. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66092. * exponential to prevent steep falloff artifacts).
  66093. */
  66094. set: function (value) {
  66095. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66096. return;
  66097. }
  66098. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66099. },
  66100. enumerable: true,
  66101. configurable: true
  66102. });
  66103. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66104. /**
  66105. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66106. */
  66107. get: function () {
  66108. return this.filter === ShadowGenerator.FILTER_PCF;
  66109. },
  66110. /**
  66111. * Sets the current filter to "PCF" (percentage closer filtering).
  66112. */
  66113. set: function (value) {
  66114. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66115. return;
  66116. }
  66117. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66118. },
  66119. enumerable: true,
  66120. configurable: true
  66121. });
  66122. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66123. /**
  66124. * Gets the PCF or PCSS Quality.
  66125. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66126. */
  66127. get: function () {
  66128. return this._filteringQuality;
  66129. },
  66130. /**
  66131. * Sets the PCF or PCSS Quality.
  66132. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66133. */
  66134. set: function (filteringQuality) {
  66135. this._filteringQuality = filteringQuality;
  66136. },
  66137. enumerable: true,
  66138. configurable: true
  66139. });
  66140. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66141. /**
  66142. * Gets if the current filter is set to "PCSS" (contact hardening).
  66143. */
  66144. get: function () {
  66145. return this.filter === ShadowGenerator.FILTER_PCSS;
  66146. },
  66147. /**
  66148. * Sets the current filter to "PCSS" (contact hardening).
  66149. */
  66150. set: function (value) {
  66151. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66152. return;
  66153. }
  66154. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66155. },
  66156. enumerable: true,
  66157. configurable: true
  66158. });
  66159. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66160. /**
  66161. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66162. * Using a ratio helps keeping shape stability independently of the map size.
  66163. *
  66164. * It does not account for the light projection as it was having too much
  66165. * instability during the light setup or during light position changes.
  66166. *
  66167. * Only valid if useContactHardeningShadow is true.
  66168. */
  66169. get: function () {
  66170. return this._contactHardeningLightSizeUVRatio;
  66171. },
  66172. /**
  66173. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66174. * Using a ratio helps keeping shape stability independently of the map size.
  66175. *
  66176. * It does not account for the light projection as it was having too much
  66177. * instability during the light setup or during light position changes.
  66178. *
  66179. * Only valid if useContactHardeningShadow is true.
  66180. */
  66181. set: function (contactHardeningLightSizeUVRatio) {
  66182. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66183. },
  66184. enumerable: true,
  66185. configurable: true
  66186. });
  66187. /**
  66188. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66189. * 0 means strongest and 1 would means no shadow.
  66190. * @returns the darkness.
  66191. */
  66192. ShadowGenerator.prototype.getDarkness = function () {
  66193. return this._darkness;
  66194. };
  66195. /**
  66196. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66197. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66198. * @returns the shadow generator allowing fluent coding.
  66199. */
  66200. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66201. if (darkness >= 1.0)
  66202. this._darkness = 1.0;
  66203. else if (darkness <= 0.0)
  66204. this._darkness = 0.0;
  66205. else
  66206. this._darkness = darkness;
  66207. return this;
  66208. };
  66209. /**
  66210. * Sets the ability to have transparent shadow (boolean).
  66211. * @param transparent True if transparent else False
  66212. * @returns the shadow generator allowing fluent coding
  66213. */
  66214. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66215. this._transparencyShadow = transparent;
  66216. return this;
  66217. };
  66218. /**
  66219. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66220. * @returns The render target texture if present otherwise, null
  66221. */
  66222. ShadowGenerator.prototype.getShadowMap = function () {
  66223. return this._shadowMap;
  66224. };
  66225. /**
  66226. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66227. * @returns The render target texture if the shadow map is present otherwise, null
  66228. */
  66229. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66230. if (this._shadowMap2) {
  66231. return this._shadowMap2;
  66232. }
  66233. return this._shadowMap;
  66234. };
  66235. /**
  66236. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66237. * @param mesh Mesh to add
  66238. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66239. * @returns the Shadow Generator itself
  66240. */
  66241. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66242. if (includeDescendants === void 0) { includeDescendants = true; }
  66243. if (!this._shadowMap) {
  66244. return this;
  66245. }
  66246. if (!this._shadowMap.renderList) {
  66247. this._shadowMap.renderList = [];
  66248. }
  66249. this._shadowMap.renderList.push(mesh);
  66250. if (includeDescendants) {
  66251. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66252. }
  66253. return this;
  66254. var _a;
  66255. };
  66256. /**
  66257. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66258. * @param mesh Mesh to remove
  66259. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66260. * @returns the Shadow Generator itself
  66261. */
  66262. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66263. if (includeDescendants === void 0) { includeDescendants = true; }
  66264. if (!this._shadowMap || !this._shadowMap.renderList) {
  66265. return this;
  66266. }
  66267. var index = this._shadowMap.renderList.indexOf(mesh);
  66268. if (index !== -1) {
  66269. this._shadowMap.renderList.splice(index, 1);
  66270. }
  66271. if (includeDescendants) {
  66272. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66273. var child = _a[_i];
  66274. this.removeShadowCaster(child);
  66275. }
  66276. }
  66277. return this;
  66278. };
  66279. /**
  66280. * Returns the associated light object.
  66281. * @returns the light generating the shadow
  66282. */
  66283. ShadowGenerator.prototype.getLight = function () {
  66284. return this._light;
  66285. };
  66286. ShadowGenerator.prototype._initializeGenerator = function () {
  66287. this._light._markMeshesAsLightDirty();
  66288. this._initializeShadowMap();
  66289. };
  66290. ShadowGenerator.prototype._initializeShadowMap = function () {
  66291. var _this = this;
  66292. // Render target
  66293. var engine = this._scene.getEngine();
  66294. if (engine.webGLVersion > 1) {
  66295. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66296. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66297. }
  66298. else {
  66299. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66300. }
  66301. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66302. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66303. this._shadowMap.anisotropicFilteringLevel = 1;
  66304. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66305. this._shadowMap.renderParticles = false;
  66306. this._shadowMap.ignoreCameraViewport = true;
  66307. // Record Face Index before render.
  66308. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66309. _this._currentFaceIndex = faceIndex;
  66310. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66311. engine.setColorWrite(false);
  66312. }
  66313. });
  66314. // Custom render function.
  66315. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66316. // Blur if required afer render.
  66317. this._shadowMap.onAfterUnbindObservable.add(function () {
  66318. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66319. engine.setColorWrite(true);
  66320. }
  66321. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66322. return;
  66323. }
  66324. var shadowMap = _this.getShadowMapForRendering();
  66325. if (shadowMap) {
  66326. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66327. }
  66328. });
  66329. // Clear according to the chosen filter.
  66330. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66331. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66332. this._shadowMap.onClearObservable.add(function (engine) {
  66333. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66334. engine.clear(clearOne, false, true, false);
  66335. }
  66336. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66337. engine.clear(clearZero, true, true, false);
  66338. }
  66339. else {
  66340. engine.clear(clearOne, true, true, false);
  66341. }
  66342. });
  66343. };
  66344. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66345. var _this = this;
  66346. var engine = this._scene.getEngine();
  66347. var targetSize = this._mapSize / this.blurScale;
  66348. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66349. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66350. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66351. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66352. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66353. }
  66354. if (this.useKernelBlur) {
  66355. 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);
  66356. this._kernelBlurXPostprocess.width = targetSize;
  66357. this._kernelBlurXPostprocess.height = targetSize;
  66358. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66359. effect.setTexture("textureSampler", _this._shadowMap);
  66360. });
  66361. 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);
  66362. this._kernelBlurXPostprocess.autoClear = false;
  66363. this._kernelBlurYPostprocess.autoClear = false;
  66364. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66365. this._kernelBlurXPostprocess.packedFloat = true;
  66366. this._kernelBlurYPostprocess.packedFloat = true;
  66367. }
  66368. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66369. }
  66370. else {
  66371. 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);
  66372. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66373. effect.setFloat2("screenSize", targetSize, targetSize);
  66374. effect.setTexture("textureSampler", _this._shadowMap);
  66375. });
  66376. this._boxBlurPostprocess.autoClear = false;
  66377. this._blurPostProcesses = [this._boxBlurPostprocess];
  66378. }
  66379. };
  66380. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66381. var index;
  66382. var engine = this._scene.getEngine();
  66383. if (depthOnlySubMeshes.length) {
  66384. engine.setColorWrite(false);
  66385. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66386. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66387. }
  66388. engine.setColorWrite(true);
  66389. }
  66390. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66391. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66392. }
  66393. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66394. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66395. }
  66396. if (this._transparencyShadow) {
  66397. for (index = 0; index < transparentSubMeshes.length; index++) {
  66398. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66399. }
  66400. }
  66401. };
  66402. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66403. var _this = this;
  66404. var mesh = subMesh.getRenderingMesh();
  66405. var scene = this._scene;
  66406. var engine = scene.getEngine();
  66407. var material = subMesh.getMaterial();
  66408. if (!material) {
  66409. return;
  66410. }
  66411. // Culling
  66412. engine.setState(material.backFaceCulling);
  66413. // Managing instances
  66414. var batch = mesh._getInstancesRenderList(subMesh._id);
  66415. if (batch.mustReturn) {
  66416. return;
  66417. }
  66418. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66419. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66420. engine.enableEffect(this._effect);
  66421. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66422. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66423. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66424. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66425. this._effect.setVector3("lightData", this._cachedDirection);
  66426. }
  66427. else {
  66428. this._effect.setVector3("lightData", this._cachedPosition);
  66429. }
  66430. if (scene.activeCamera) {
  66431. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66432. }
  66433. // Alpha test
  66434. if (material && material.needAlphaTesting()) {
  66435. var alphaTexture = material.getAlphaTestTexture();
  66436. if (alphaTexture) {
  66437. this._effect.setTexture("diffuseSampler", alphaTexture);
  66438. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66439. }
  66440. }
  66441. // Bones
  66442. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66443. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66444. }
  66445. // Morph targets
  66446. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66447. if (this.forceBackFacesOnly) {
  66448. engine.setState(true, 0, false, true);
  66449. }
  66450. // Draw
  66451. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66452. if (this.forceBackFacesOnly) {
  66453. engine.setState(true, 0, false, false);
  66454. }
  66455. }
  66456. else {
  66457. // Need to reset refresh rate of the shadowMap
  66458. if (this._shadowMap) {
  66459. this._shadowMap.resetRefreshCounter();
  66460. }
  66461. }
  66462. };
  66463. ShadowGenerator.prototype._applyFilterValues = function () {
  66464. if (!this._shadowMap) {
  66465. return;
  66466. }
  66467. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66468. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66469. }
  66470. else {
  66471. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66472. }
  66473. };
  66474. /**
  66475. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66476. * @param onCompiled Callback triggered at the and of the effects compilation
  66477. * @param options Sets of optional options forcing the compilation with different modes
  66478. */
  66479. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66480. var _this = this;
  66481. var localOptions = __assign({ useInstances: false }, options);
  66482. var shadowMap = this.getShadowMap();
  66483. if (!shadowMap) {
  66484. if (onCompiled) {
  66485. onCompiled(this);
  66486. }
  66487. return;
  66488. }
  66489. var renderList = shadowMap.renderList;
  66490. if (!renderList) {
  66491. if (onCompiled) {
  66492. onCompiled(this);
  66493. }
  66494. return;
  66495. }
  66496. var subMeshes = new Array();
  66497. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66498. var mesh = renderList_1[_i];
  66499. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66500. }
  66501. if (subMeshes.length === 0) {
  66502. if (onCompiled) {
  66503. onCompiled(this);
  66504. }
  66505. return;
  66506. }
  66507. var currentIndex = 0;
  66508. var checkReady = function () {
  66509. if (!_this._scene || !_this._scene.getEngine()) {
  66510. return;
  66511. }
  66512. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66513. currentIndex++;
  66514. if (currentIndex >= subMeshes.length) {
  66515. if (onCompiled) {
  66516. onCompiled(_this);
  66517. }
  66518. return;
  66519. }
  66520. }
  66521. setTimeout(checkReady, 16);
  66522. };
  66523. checkReady();
  66524. };
  66525. /**
  66526. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66527. * @param options Sets of optional options forcing the compilation with different modes
  66528. * @returns A promise that resolves when the compilation completes
  66529. */
  66530. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66531. var _this = this;
  66532. return new Promise(function (resolve) {
  66533. _this.forceCompilation(function () {
  66534. resolve();
  66535. }, options);
  66536. });
  66537. };
  66538. /**
  66539. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66540. * @param subMesh The submesh we want to render in the shadow map
  66541. * @param useInstances Defines wether will draw in the map using instances
  66542. * @returns true if ready otherwise, false
  66543. */
  66544. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66545. var defines = [];
  66546. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66547. defines.push("#define FLOAT");
  66548. }
  66549. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66550. defines.push("#define ESM");
  66551. }
  66552. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66553. defines.push("#define DEPTHTEXTURE");
  66554. }
  66555. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66556. var mesh = subMesh.getMesh();
  66557. var material = subMesh.getMaterial();
  66558. // Normal bias.
  66559. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66560. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66561. defines.push("#define NORMAL");
  66562. if (mesh.nonUniformScaling) {
  66563. defines.push("#define NONUNIFORMSCALING");
  66564. }
  66565. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66566. defines.push("#define DIRECTIONINLIGHTDATA");
  66567. }
  66568. }
  66569. // Alpha test
  66570. if (material && material.needAlphaTesting()) {
  66571. var alphaTexture = material.getAlphaTestTexture();
  66572. if (alphaTexture) {
  66573. defines.push("#define ALPHATEST");
  66574. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66575. attribs.push(BABYLON.VertexBuffer.UVKind);
  66576. defines.push("#define UV1");
  66577. }
  66578. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66579. if (alphaTexture.coordinatesIndex === 1) {
  66580. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66581. defines.push("#define UV2");
  66582. }
  66583. }
  66584. }
  66585. }
  66586. // Bones
  66587. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66588. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66589. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66590. if (mesh.numBoneInfluencers > 4) {
  66591. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66592. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66593. }
  66594. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66595. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66596. }
  66597. else {
  66598. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66599. }
  66600. // Morph targets
  66601. var manager = mesh.morphTargetManager;
  66602. var morphInfluencers = 0;
  66603. if (manager) {
  66604. if (manager.numInfluencers > 0) {
  66605. defines.push("#define MORPHTARGETS");
  66606. morphInfluencers = manager.numInfluencers;
  66607. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66608. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66609. }
  66610. }
  66611. // Instances
  66612. if (useInstances) {
  66613. defines.push("#define INSTANCES");
  66614. attribs.push("world0");
  66615. attribs.push("world1");
  66616. attribs.push("world2");
  66617. attribs.push("world3");
  66618. }
  66619. // Get correct effect
  66620. var join = defines.join("\n");
  66621. if (this._cachedDefines !== join) {
  66622. this._cachedDefines = join;
  66623. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66624. }
  66625. if (!this._effect.isReady()) {
  66626. return false;
  66627. }
  66628. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66629. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66630. this._initializeBlurRTTAndPostProcesses();
  66631. }
  66632. }
  66633. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66634. return false;
  66635. }
  66636. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66637. return false;
  66638. }
  66639. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66640. return false;
  66641. }
  66642. return true;
  66643. };
  66644. /**
  66645. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66646. * @param defines Defines of the material we want to update
  66647. * @param lightIndex Index of the light in the enabled light list of the material
  66648. */
  66649. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66650. var scene = this._scene;
  66651. var light = this._light;
  66652. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66653. return;
  66654. }
  66655. defines["SHADOW" + lightIndex] = true;
  66656. if (this.useContactHardeningShadow) {
  66657. defines["SHADOWPCSS" + lightIndex] = true;
  66658. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66659. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66660. }
  66661. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66662. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66663. }
  66664. // else default to high.
  66665. }
  66666. if (this.usePercentageCloserFiltering) {
  66667. defines["SHADOWPCF" + lightIndex] = true;
  66668. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66669. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66670. }
  66671. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66672. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66673. }
  66674. // else default to high.
  66675. }
  66676. else if (this.usePoissonSampling) {
  66677. defines["SHADOWPOISSON" + lightIndex] = true;
  66678. }
  66679. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66680. defines["SHADOWESM" + lightIndex] = true;
  66681. }
  66682. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66683. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66684. }
  66685. if (light.needCube()) {
  66686. defines["SHADOWCUBE" + lightIndex] = true;
  66687. }
  66688. };
  66689. /**
  66690. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66691. * defined in the generator but impacting the effect).
  66692. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66693. * @param effect The effect we are binfing the information for
  66694. */
  66695. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66696. var light = this._light;
  66697. var scene = this._scene;
  66698. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66699. return;
  66700. }
  66701. var camera = scene.activeCamera;
  66702. if (!camera) {
  66703. return;
  66704. }
  66705. var shadowMap = this.getShadowMap();
  66706. if (!shadowMap) {
  66707. return;
  66708. }
  66709. if (!light.needCube()) {
  66710. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66711. }
  66712. // Only PCF uses depth stencil texture.
  66713. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66714. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66715. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66716. }
  66717. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66718. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66719. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66720. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66721. }
  66722. else {
  66723. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66724. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66725. }
  66726. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66727. };
  66728. /**
  66729. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66730. * (eq to shadow prjection matrix * light transform matrix)
  66731. * @returns The transform matrix used to create the shadow map
  66732. */
  66733. ShadowGenerator.prototype.getTransformMatrix = function () {
  66734. var scene = this._scene;
  66735. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66736. return this._transformMatrix;
  66737. }
  66738. this._currentRenderID = scene.getRenderId();
  66739. this._currentFaceIndexCache = this._currentFaceIndex;
  66740. var lightPosition = this._light.position;
  66741. if (this._light.computeTransformedInformation()) {
  66742. lightPosition = this._light.transformedPosition;
  66743. }
  66744. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66745. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66746. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66747. }
  66748. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66749. this._cachedPosition.copyFrom(lightPosition);
  66750. this._cachedDirection.copyFrom(this._lightDirection);
  66751. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66752. var shadowMap = this.getShadowMap();
  66753. if (shadowMap) {
  66754. var renderList = shadowMap.renderList;
  66755. if (renderList) {
  66756. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66757. }
  66758. }
  66759. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66760. }
  66761. return this._transformMatrix;
  66762. };
  66763. /**
  66764. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66765. * Cube and 2D textures for instance.
  66766. */
  66767. ShadowGenerator.prototype.recreateShadowMap = function () {
  66768. var shadowMap = this._shadowMap;
  66769. if (!shadowMap) {
  66770. return;
  66771. }
  66772. // Track render list.
  66773. var renderList = shadowMap.renderList;
  66774. // Clean up existing data.
  66775. this._disposeRTTandPostProcesses();
  66776. // Reinitializes.
  66777. this._initializeGenerator();
  66778. // Reaffect the filter to ensure a correct fallback if necessary.
  66779. this.filter = this.filter;
  66780. // Reaffect the filter.
  66781. this._applyFilterValues();
  66782. // Reaffect Render List.
  66783. this._shadowMap.renderList = renderList;
  66784. };
  66785. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66786. if (this._shadowMap2) {
  66787. this._shadowMap2.dispose();
  66788. this._shadowMap2 = null;
  66789. }
  66790. if (this._boxBlurPostprocess) {
  66791. this._boxBlurPostprocess.dispose();
  66792. this._boxBlurPostprocess = null;
  66793. }
  66794. if (this._kernelBlurXPostprocess) {
  66795. this._kernelBlurXPostprocess.dispose();
  66796. this._kernelBlurXPostprocess = null;
  66797. }
  66798. if (this._kernelBlurYPostprocess) {
  66799. this._kernelBlurYPostprocess.dispose();
  66800. this._kernelBlurYPostprocess = null;
  66801. }
  66802. this._blurPostProcesses = [];
  66803. };
  66804. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66805. if (this._shadowMap) {
  66806. this._shadowMap.dispose();
  66807. this._shadowMap = null;
  66808. }
  66809. this._disposeBlurPostProcesses();
  66810. };
  66811. /**
  66812. * Disposes the ShadowGenerator.
  66813. * Returns nothing.
  66814. */
  66815. ShadowGenerator.prototype.dispose = function () {
  66816. this._disposeRTTandPostProcesses();
  66817. if (this._light) {
  66818. this._light._shadowGenerator = null;
  66819. this._light._markMeshesAsLightDirty();
  66820. }
  66821. };
  66822. /**
  66823. * Serializes the shadow generator setup to a json object.
  66824. * @returns The serialized JSON object
  66825. */
  66826. ShadowGenerator.prototype.serialize = function () {
  66827. var serializationObject = {};
  66828. var shadowMap = this.getShadowMap();
  66829. if (!shadowMap) {
  66830. return serializationObject;
  66831. }
  66832. serializationObject.lightId = this._light.id;
  66833. serializationObject.mapSize = shadowMap.getRenderSize();
  66834. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66835. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66836. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66837. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66838. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66839. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66840. serializationObject.depthScale = this.depthScale;
  66841. serializationObject.darkness = this.getDarkness();
  66842. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66843. serializationObject.blurKernel = this.blurKernel;
  66844. serializationObject.blurScale = this.blurScale;
  66845. serializationObject.useKernelBlur = this.useKernelBlur;
  66846. serializationObject.transparencyShadow = this._transparencyShadow;
  66847. serializationObject.bias = this.bias;
  66848. serializationObject.normalBias = this.normalBias;
  66849. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66850. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66851. serializationObject.filteringQuality = this.filteringQuality;
  66852. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66853. serializationObject.renderList = [];
  66854. if (shadowMap.renderList) {
  66855. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66856. var mesh = shadowMap.renderList[meshIndex];
  66857. serializationObject.renderList.push(mesh.id);
  66858. }
  66859. }
  66860. return serializationObject;
  66861. };
  66862. /**
  66863. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66864. * @param parsedShadowGenerator The JSON object to parse
  66865. * @param scene The scene to create the shadow map for
  66866. * @returns The parsed shadow generator
  66867. */
  66868. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66869. //casting to point light, as light is missing the position attr and typescript complains.
  66870. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66871. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66872. var shadowMap = shadowGenerator.getShadowMap();
  66873. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66874. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66875. meshes.forEach(function (mesh) {
  66876. if (!shadowMap) {
  66877. return;
  66878. }
  66879. if (!shadowMap.renderList) {
  66880. shadowMap.renderList = [];
  66881. }
  66882. shadowMap.renderList.push(mesh);
  66883. });
  66884. }
  66885. if (parsedShadowGenerator.usePoissonSampling) {
  66886. shadowGenerator.usePoissonSampling = true;
  66887. }
  66888. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66889. shadowGenerator.useExponentialShadowMap = true;
  66890. }
  66891. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66892. shadowGenerator.useBlurExponentialShadowMap = true;
  66893. }
  66894. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66895. shadowGenerator.useCloseExponentialShadowMap = true;
  66896. }
  66897. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66898. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66899. }
  66900. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66901. shadowGenerator.usePercentageCloserFiltering = true;
  66902. }
  66903. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66904. shadowGenerator.useContactHardeningShadow = true;
  66905. }
  66906. if (parsedShadowGenerator.filteringQuality) {
  66907. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66908. }
  66909. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66910. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66911. }
  66912. // Backward compat
  66913. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66914. shadowGenerator.useExponentialShadowMap = true;
  66915. }
  66916. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66917. shadowGenerator.useBlurExponentialShadowMap = true;
  66918. }
  66919. if (parsedShadowGenerator.depthScale) {
  66920. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66921. }
  66922. if (parsedShadowGenerator.blurScale) {
  66923. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66924. }
  66925. if (parsedShadowGenerator.blurBoxOffset) {
  66926. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66927. }
  66928. if (parsedShadowGenerator.useKernelBlur) {
  66929. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66930. }
  66931. if (parsedShadowGenerator.blurKernel) {
  66932. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66933. }
  66934. if (parsedShadowGenerator.bias !== undefined) {
  66935. shadowGenerator.bias = parsedShadowGenerator.bias;
  66936. }
  66937. if (parsedShadowGenerator.normalBias !== undefined) {
  66938. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66939. }
  66940. if (parsedShadowGenerator.darkness) {
  66941. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66942. }
  66943. if (parsedShadowGenerator.transparencyShadow) {
  66944. shadowGenerator.setTransparencyShadow(true);
  66945. }
  66946. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66947. return shadowGenerator;
  66948. };
  66949. /**
  66950. * Shadow generator mode None: no filtering applied.
  66951. */
  66952. ShadowGenerator.FILTER_NONE = 0;
  66953. /**
  66954. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66955. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66956. */
  66957. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66958. /**
  66959. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66960. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66961. */
  66962. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66963. /**
  66964. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66965. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66966. */
  66967. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66968. /**
  66969. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66970. * edge artifacts on steep falloff.
  66971. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66972. */
  66973. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66974. /**
  66975. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66976. * edge artifacts on steep falloff.
  66977. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66978. */
  66979. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66980. /**
  66981. * Shadow generator mode PCF: Percentage Closer Filtering
  66982. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66983. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66984. */
  66985. ShadowGenerator.FILTER_PCF = 6;
  66986. /**
  66987. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66988. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66989. * Contact Hardening
  66990. */
  66991. ShadowGenerator.FILTER_PCSS = 7;
  66992. /**
  66993. * Reserved for PCF and PCSS
  66994. * Highest Quality.
  66995. *
  66996. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66997. *
  66998. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66999. */
  67000. ShadowGenerator.QUALITY_HIGH = 0;
  67001. /**
  67002. * Reserved for PCF and PCSS
  67003. * Good tradeoff for quality/perf cross devices
  67004. *
  67005. * Execute PCF on a 3*3 kernel.
  67006. *
  67007. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67008. */
  67009. ShadowGenerator.QUALITY_MEDIUM = 1;
  67010. /**
  67011. * Reserved for PCF and PCSS
  67012. * The lowest quality but the fastest.
  67013. *
  67014. * Execute PCF on a 1*1 kernel.
  67015. *
  67016. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67017. */
  67018. ShadowGenerator.QUALITY_LOW = 2;
  67019. return ShadowGenerator;
  67020. }());
  67021. BABYLON.ShadowGenerator = ShadowGenerator;
  67022. })(BABYLON || (BABYLON = {}));
  67023. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67024. var BABYLON;
  67025. (function (BABYLON) {
  67026. var DefaultLoadingScreen = /** @class */ (function () {
  67027. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67028. if (_loadingText === void 0) { _loadingText = ""; }
  67029. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67030. var _this = this;
  67031. this._renderingCanvas = _renderingCanvas;
  67032. this._loadingText = _loadingText;
  67033. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67034. // Resize
  67035. this._resizeLoadingUI = function () {
  67036. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67037. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67038. if (!_this._loadingDiv) {
  67039. return;
  67040. }
  67041. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67042. _this._loadingDiv.style.left = canvasRect.left + "px";
  67043. _this._loadingDiv.style.top = canvasRect.top + "px";
  67044. _this._loadingDiv.style.width = canvasRect.width + "px";
  67045. _this._loadingDiv.style.height = canvasRect.height + "px";
  67046. };
  67047. }
  67048. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67049. if (this._loadingDiv) {
  67050. // Do not add a loading screen if there is already one
  67051. return;
  67052. }
  67053. this._loadingDiv = document.createElement("div");
  67054. this._loadingDiv.id = "babylonjsLoadingDiv";
  67055. this._loadingDiv.style.opacity = "0";
  67056. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67057. this._loadingDiv.style.pointerEvents = "none";
  67058. // Loading text
  67059. this._loadingTextDiv = document.createElement("div");
  67060. this._loadingTextDiv.style.position = "absolute";
  67061. this._loadingTextDiv.style.left = "0";
  67062. this._loadingTextDiv.style.top = "50%";
  67063. this._loadingTextDiv.style.marginTop = "80px";
  67064. this._loadingTextDiv.style.width = "100%";
  67065. this._loadingTextDiv.style.height = "20px";
  67066. this._loadingTextDiv.style.fontFamily = "Arial";
  67067. this._loadingTextDiv.style.fontSize = "14px";
  67068. this._loadingTextDiv.style.color = "white";
  67069. this._loadingTextDiv.style.textAlign = "center";
  67070. this._loadingTextDiv.innerHTML = "Loading";
  67071. this._loadingDiv.appendChild(this._loadingTextDiv);
  67072. //set the predefined text
  67073. this._loadingTextDiv.innerHTML = this._loadingText;
  67074. // Generating keyframes
  67075. var style = document.createElement('style');
  67076. style.type = 'text/css';
  67077. 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 }";
  67078. style.innerHTML = keyFrames;
  67079. document.getElementsByTagName('head')[0].appendChild(style);
  67080. // Loading img
  67081. var imgBack = new Image();
  67082. 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";
  67083. imgBack.style.position = "absolute";
  67084. imgBack.style.left = "50%";
  67085. imgBack.style.top = "50%";
  67086. imgBack.style.marginLeft = "-60px";
  67087. imgBack.style.marginTop = "-60px";
  67088. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67089. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67090. imgBack.style.transformOrigin = "50% 50%";
  67091. imgBack.style.webkitTransformOrigin = "50% 50%";
  67092. this._loadingDiv.appendChild(imgBack);
  67093. this._resizeLoadingUI();
  67094. window.addEventListener("resize", this._resizeLoadingUI);
  67095. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67096. document.body.appendChild(this._loadingDiv);
  67097. this._loadingDiv.style.opacity = "1";
  67098. };
  67099. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67100. var _this = this;
  67101. if (!this._loadingDiv) {
  67102. return;
  67103. }
  67104. var onTransitionEnd = function () {
  67105. if (!_this._loadingDiv) {
  67106. return;
  67107. }
  67108. document.body.removeChild(_this._loadingDiv);
  67109. window.removeEventListener("resize", _this._resizeLoadingUI);
  67110. _this._loadingDiv = null;
  67111. };
  67112. this._loadingDiv.style.opacity = "0";
  67113. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67114. };
  67115. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67116. set: function (text) {
  67117. this._loadingText = text;
  67118. if (this._loadingTextDiv) {
  67119. this._loadingTextDiv.innerHTML = this._loadingText;
  67120. }
  67121. },
  67122. enumerable: true,
  67123. configurable: true
  67124. });
  67125. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67126. get: function () {
  67127. return this._loadingDivBackgroundColor;
  67128. },
  67129. set: function (color) {
  67130. this._loadingDivBackgroundColor = color;
  67131. if (!this._loadingDiv) {
  67132. return;
  67133. }
  67134. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67135. },
  67136. enumerable: true,
  67137. configurable: true
  67138. });
  67139. return DefaultLoadingScreen;
  67140. }());
  67141. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67142. })(BABYLON || (BABYLON = {}));
  67143. //# sourceMappingURL=babylon.loadingScreen.js.map
  67144. var BABYLON;
  67145. (function (BABYLON) {
  67146. var SceneLoaderProgressEvent = /** @class */ (function () {
  67147. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67148. this.lengthComputable = lengthComputable;
  67149. this.loaded = loaded;
  67150. this.total = total;
  67151. }
  67152. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67153. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67154. };
  67155. return SceneLoaderProgressEvent;
  67156. }());
  67157. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67158. var SceneLoader = /** @class */ (function () {
  67159. function SceneLoader() {
  67160. }
  67161. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67162. get: function () {
  67163. return 0;
  67164. },
  67165. enumerable: true,
  67166. configurable: true
  67167. });
  67168. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67169. get: function () {
  67170. return 1;
  67171. },
  67172. enumerable: true,
  67173. configurable: true
  67174. });
  67175. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67176. get: function () {
  67177. return 2;
  67178. },
  67179. enumerable: true,
  67180. configurable: true
  67181. });
  67182. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67183. get: function () {
  67184. return 3;
  67185. },
  67186. enumerable: true,
  67187. configurable: true
  67188. });
  67189. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67190. get: function () {
  67191. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67192. },
  67193. set: function (value) {
  67194. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67195. },
  67196. enumerable: true,
  67197. configurable: true
  67198. });
  67199. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67200. get: function () {
  67201. return SceneLoader._ShowLoadingScreen;
  67202. },
  67203. set: function (value) {
  67204. SceneLoader._ShowLoadingScreen = value;
  67205. },
  67206. enumerable: true,
  67207. configurable: true
  67208. });
  67209. Object.defineProperty(SceneLoader, "loggingLevel", {
  67210. get: function () {
  67211. return SceneLoader._loggingLevel;
  67212. },
  67213. set: function (value) {
  67214. SceneLoader._loggingLevel = value;
  67215. },
  67216. enumerable: true,
  67217. configurable: true
  67218. });
  67219. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67220. get: function () {
  67221. return SceneLoader._CleanBoneMatrixWeights;
  67222. },
  67223. set: function (value) {
  67224. SceneLoader._CleanBoneMatrixWeights = value;
  67225. },
  67226. enumerable: true,
  67227. configurable: true
  67228. });
  67229. SceneLoader._getDefaultPlugin = function () {
  67230. return SceneLoader._registeredPlugins[".babylon"];
  67231. };
  67232. SceneLoader._getPluginForExtension = function (extension) {
  67233. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67234. if (registeredPlugin) {
  67235. return registeredPlugin;
  67236. }
  67237. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  67238. return SceneLoader._getDefaultPlugin();
  67239. };
  67240. SceneLoader._getPluginForDirectLoad = function (data) {
  67241. for (var extension in SceneLoader._registeredPlugins) {
  67242. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67243. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67244. return SceneLoader._registeredPlugins[extension];
  67245. }
  67246. }
  67247. return SceneLoader._getDefaultPlugin();
  67248. };
  67249. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67250. if (sceneFilename.name) {
  67251. sceneFilename = sceneFilename.name;
  67252. }
  67253. var queryStringPosition = sceneFilename.indexOf("?");
  67254. if (queryStringPosition !== -1) {
  67255. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67256. }
  67257. var dotPosition = sceneFilename.lastIndexOf(".");
  67258. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67259. return SceneLoader._getPluginForExtension(extension);
  67260. };
  67261. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67262. SceneLoader._getDirectLoad = function (sceneFilename) {
  67263. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67264. return sceneFilename.substr(5);
  67265. }
  67266. return null;
  67267. };
  67268. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67269. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67270. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67271. var plugin;
  67272. if (registeredPlugin.plugin.createPlugin) {
  67273. plugin = registeredPlugin.plugin.createPlugin();
  67274. }
  67275. else {
  67276. plugin = registeredPlugin.plugin;
  67277. }
  67278. var useArrayBuffer = registeredPlugin.isBinary;
  67279. var database;
  67280. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67281. var dataCallback = function (data, responseURL) {
  67282. if (scene.isDisposed) {
  67283. onError("Scene has been disposed");
  67284. return;
  67285. }
  67286. scene.database = database;
  67287. onSuccess(plugin, data, responseURL);
  67288. };
  67289. var request = null;
  67290. var pluginDisposed = false;
  67291. var onDisposeObservable = plugin.onDisposeObservable;
  67292. if (onDisposeObservable) {
  67293. onDisposeObservable.add(function () {
  67294. pluginDisposed = true;
  67295. if (request) {
  67296. request.abort();
  67297. request = null;
  67298. }
  67299. onDispose();
  67300. });
  67301. }
  67302. var manifestChecked = function () {
  67303. if (pluginDisposed) {
  67304. return;
  67305. }
  67306. var url = rootUrl + sceneFilename;
  67307. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67308. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67309. } : undefined, database, useArrayBuffer, function (request, exception) {
  67310. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67311. });
  67312. };
  67313. if (directLoad) {
  67314. dataCallback(directLoad);
  67315. return plugin;
  67316. }
  67317. if (rootUrl.indexOf("file:") === -1) {
  67318. var engine = scene.getEngine();
  67319. var canUseOfflineSupport = engine.enableOfflineSupport;
  67320. if (canUseOfflineSupport) {
  67321. // Also check for exceptions
  67322. var exceptionFound = false;
  67323. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67324. var regex = _a[_i];
  67325. if (regex.test(rootUrl + sceneFilename)) {
  67326. exceptionFound = true;
  67327. break;
  67328. }
  67329. }
  67330. canUseOfflineSupport = !exceptionFound;
  67331. }
  67332. if (canUseOfflineSupport) {
  67333. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67334. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67335. }
  67336. else {
  67337. manifestChecked();
  67338. }
  67339. }
  67340. // Loading file from disk via input file or drag'n'drop
  67341. else {
  67342. var fileOrString = sceneFilename;
  67343. if (fileOrString.name) { // File
  67344. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67345. }
  67346. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67347. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67348. }
  67349. else {
  67350. onError("Unable to find file named " + sceneFilename);
  67351. }
  67352. }
  67353. return plugin;
  67354. };
  67355. // Public functions
  67356. SceneLoader.GetPluginForExtension = function (extension) {
  67357. return SceneLoader._getPluginForExtension(extension).plugin;
  67358. };
  67359. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67360. return !!SceneLoader._registeredPlugins[extension];
  67361. };
  67362. SceneLoader.RegisterPlugin = function (plugin) {
  67363. if (typeof plugin.extensions === "string") {
  67364. var extension = plugin.extensions;
  67365. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67366. plugin: plugin,
  67367. isBinary: false
  67368. };
  67369. }
  67370. else {
  67371. var extensions = plugin.extensions;
  67372. Object.keys(extensions).forEach(function (extension) {
  67373. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67374. plugin: plugin,
  67375. isBinary: extensions[extension].isBinary
  67376. };
  67377. });
  67378. }
  67379. };
  67380. /**
  67381. * Import meshes into a scene
  67382. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67383. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67384. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67385. * @param scene the instance of BABYLON.Scene to append to
  67386. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67387. * @param onProgress a callback with a progress event for each file being loaded
  67388. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67389. * @param pluginExtension the extension used to determine the plugin
  67390. * @returns The loaded plugin
  67391. */
  67392. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67393. if (sceneFilename === void 0) { sceneFilename = ""; }
  67394. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67395. if (onSuccess === void 0) { onSuccess = null; }
  67396. if (onProgress === void 0) { onProgress = null; }
  67397. if (onError === void 0) { onError = null; }
  67398. if (pluginExtension === void 0) { pluginExtension = null; }
  67399. if (!scene) {
  67400. BABYLON.Tools.Error("No scene available to import mesh to");
  67401. return null;
  67402. }
  67403. if (!sceneFilename) {
  67404. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67405. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67406. }
  67407. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67408. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67409. return null;
  67410. }
  67411. var loadingToken = {};
  67412. scene._addPendingData(loadingToken);
  67413. var disposeHandler = function () {
  67414. scene._removePendingData(loadingToken);
  67415. };
  67416. var errorHandler = function (message, exception) {
  67417. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67418. if (onError) {
  67419. onError(scene, errorMessage, exception);
  67420. }
  67421. else {
  67422. BABYLON.Tools.Error(errorMessage);
  67423. // should the exception be thrown?
  67424. }
  67425. disposeHandler();
  67426. };
  67427. var progressHandler = onProgress ? function (event) {
  67428. try {
  67429. onProgress(event);
  67430. }
  67431. catch (e) {
  67432. errorHandler("Error in onProgress callback", e);
  67433. }
  67434. } : undefined;
  67435. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67436. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67437. if (onSuccess) {
  67438. try {
  67439. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67440. }
  67441. catch (e) {
  67442. errorHandler("Error in onSuccess callback", e);
  67443. }
  67444. }
  67445. scene._removePendingData(loadingToken);
  67446. };
  67447. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67448. if (plugin.rewriteRootURL) {
  67449. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67450. }
  67451. if (sceneFilename === "") {
  67452. if (sceneFilename === "") {
  67453. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67454. }
  67455. }
  67456. if (plugin.importMesh) {
  67457. var syncedPlugin = plugin;
  67458. var meshes = new Array();
  67459. var particleSystems = new Array();
  67460. var skeletons = new Array();
  67461. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67462. return;
  67463. }
  67464. scene.loadingPluginName = plugin.name;
  67465. successHandler(meshes, particleSystems, skeletons, []);
  67466. }
  67467. else {
  67468. var asyncedPlugin = plugin;
  67469. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67470. scene.loadingPluginName = plugin.name;
  67471. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67472. }).catch(function (error) {
  67473. errorHandler(error.message, error);
  67474. });
  67475. }
  67476. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67477. };
  67478. /**
  67479. * Import meshes into a scene
  67480. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67481. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67482. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67483. * @param scene the instance of BABYLON.Scene to append to
  67484. * @param onProgress a callback with a progress event for each file being loaded
  67485. * @param pluginExtension the extension used to determine the plugin
  67486. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67487. */
  67488. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67489. if (sceneFilename === void 0) { sceneFilename = ""; }
  67490. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67491. if (onProgress === void 0) { onProgress = null; }
  67492. if (pluginExtension === void 0) { pluginExtension = null; }
  67493. return new Promise(function (resolve, reject) {
  67494. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67495. resolve({
  67496. meshes: meshes,
  67497. particleSystems: particleSystems,
  67498. skeletons: skeletons,
  67499. animationGroups: animationGroups
  67500. });
  67501. }, onProgress, function (scene, message, exception) {
  67502. reject(exception || new Error(message));
  67503. }, pluginExtension);
  67504. });
  67505. };
  67506. /**
  67507. * Load a scene
  67508. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67509. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67510. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67511. * @param onSuccess a callback with the scene when import succeeds
  67512. * @param onProgress a callback with a progress event for each file being loaded
  67513. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67514. * @param pluginExtension the extension used to determine the plugin
  67515. * @returns The loaded plugin
  67516. */
  67517. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67518. if (onSuccess === void 0) { onSuccess = null; }
  67519. if (onProgress === void 0) { onProgress = null; }
  67520. if (onError === void 0) { onError = null; }
  67521. if (pluginExtension === void 0) { pluginExtension = null; }
  67522. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67523. };
  67524. /**
  67525. * Load a scene
  67526. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67527. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67528. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67529. * @param onProgress a callback with a progress event for each file being loaded
  67530. * @param pluginExtension the extension used to determine the plugin
  67531. * @returns The loaded scene
  67532. */
  67533. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67534. if (onProgress === void 0) { onProgress = null; }
  67535. if (pluginExtension === void 0) { pluginExtension = null; }
  67536. return new Promise(function (resolve, reject) {
  67537. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67538. resolve(scene);
  67539. }, onProgress, function (scene, message, exception) {
  67540. reject(exception || new Error(message));
  67541. }, pluginExtension);
  67542. });
  67543. };
  67544. /**
  67545. * Append a scene
  67546. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67547. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67548. * @param scene is the instance of BABYLON.Scene to append to
  67549. * @param onSuccess a callback with the scene when import succeeds
  67550. * @param onProgress a callback with a progress event for each file being loaded
  67551. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67552. * @param pluginExtension the extension used to determine the plugin
  67553. * @returns The loaded plugin
  67554. */
  67555. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67556. if (sceneFilename === void 0) { sceneFilename = ""; }
  67557. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67558. if (onSuccess === void 0) { onSuccess = null; }
  67559. if (onProgress === void 0) { onProgress = null; }
  67560. if (onError === void 0) { onError = null; }
  67561. if (pluginExtension === void 0) { pluginExtension = null; }
  67562. if (!scene) {
  67563. BABYLON.Tools.Error("No scene available to append to");
  67564. return null;
  67565. }
  67566. if (!sceneFilename) {
  67567. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67568. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67569. }
  67570. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67571. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67572. return null;
  67573. }
  67574. if (SceneLoader.ShowLoadingScreen) {
  67575. scene.getEngine().displayLoadingUI();
  67576. }
  67577. var loadingToken = {};
  67578. scene._addPendingData(loadingToken);
  67579. var disposeHandler = function () {
  67580. scene._removePendingData(loadingToken);
  67581. scene.getEngine().hideLoadingUI();
  67582. };
  67583. var errorHandler = function (message, exception) {
  67584. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67585. if (onError) {
  67586. onError(scene, errorMessage, exception);
  67587. }
  67588. else {
  67589. BABYLON.Tools.Error(errorMessage);
  67590. // should the exception be thrown?
  67591. }
  67592. disposeHandler();
  67593. };
  67594. var progressHandler = onProgress ? function (event) {
  67595. try {
  67596. onProgress(event);
  67597. }
  67598. catch (e) {
  67599. errorHandler("Error in onProgress callback", e);
  67600. }
  67601. } : undefined;
  67602. var successHandler = function () {
  67603. if (onSuccess) {
  67604. try {
  67605. onSuccess(scene);
  67606. }
  67607. catch (e) {
  67608. errorHandler("Error in onSuccess callback", e);
  67609. }
  67610. }
  67611. scene._removePendingData(loadingToken);
  67612. };
  67613. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67614. if (sceneFilename === "") {
  67615. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67616. }
  67617. if (plugin.load) {
  67618. var syncedPlugin = plugin;
  67619. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67620. return;
  67621. }
  67622. scene.loadingPluginName = plugin.name;
  67623. successHandler();
  67624. }
  67625. else {
  67626. var asyncedPlugin = plugin;
  67627. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67628. scene.loadingPluginName = plugin.name;
  67629. successHandler();
  67630. }).catch(function (error) {
  67631. errorHandler(error.message, error);
  67632. });
  67633. }
  67634. if (SceneLoader.ShowLoadingScreen) {
  67635. scene.executeWhenReady(function () {
  67636. scene.getEngine().hideLoadingUI();
  67637. });
  67638. }
  67639. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67640. };
  67641. /**
  67642. * Append a scene
  67643. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67644. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67645. * @param scene is the instance of BABYLON.Scene to append to
  67646. * @param onProgress a callback with a progress event for each file being loaded
  67647. * @param pluginExtension the extension used to determine the plugin
  67648. * @returns The given scene
  67649. */
  67650. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67651. if (sceneFilename === void 0) { sceneFilename = ""; }
  67652. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67653. if (onProgress === void 0) { onProgress = null; }
  67654. if (pluginExtension === void 0) { pluginExtension = null; }
  67655. return new Promise(function (resolve, reject) {
  67656. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67657. resolve(scene);
  67658. }, onProgress, function (scene, message, exception) {
  67659. reject(exception || new Error(message));
  67660. }, pluginExtension);
  67661. });
  67662. };
  67663. /**
  67664. * Load a scene into an asset container
  67665. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67666. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67667. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67668. * @param onSuccess a callback with the scene when import succeeds
  67669. * @param onProgress a callback with a progress event for each file being loaded
  67670. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67671. * @param pluginExtension the extension used to determine the plugin
  67672. * @returns The loaded plugin
  67673. */
  67674. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67675. if (sceneFilename === void 0) { sceneFilename = ""; }
  67676. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67677. if (onSuccess === void 0) { onSuccess = null; }
  67678. if (onProgress === void 0) { onProgress = null; }
  67679. if (onError === void 0) { onError = null; }
  67680. if (pluginExtension === void 0) { pluginExtension = null; }
  67681. if (!scene) {
  67682. BABYLON.Tools.Error("No scene available to load asset container to");
  67683. return null;
  67684. }
  67685. if (!sceneFilename) {
  67686. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67687. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67688. }
  67689. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67690. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67691. return null;
  67692. }
  67693. var loadingToken = {};
  67694. scene._addPendingData(loadingToken);
  67695. var disposeHandler = function () {
  67696. scene._removePendingData(loadingToken);
  67697. };
  67698. var errorHandler = function (message, exception) {
  67699. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67700. if (onError) {
  67701. onError(scene, errorMessage, exception);
  67702. }
  67703. else {
  67704. BABYLON.Tools.Error(errorMessage);
  67705. // should the exception be thrown?
  67706. }
  67707. disposeHandler();
  67708. };
  67709. var progressHandler = onProgress ? function (event) {
  67710. try {
  67711. onProgress(event);
  67712. }
  67713. catch (e) {
  67714. errorHandler("Error in onProgress callback", e);
  67715. }
  67716. } : undefined;
  67717. var successHandler = function (assets) {
  67718. if (onSuccess) {
  67719. try {
  67720. onSuccess(assets);
  67721. }
  67722. catch (e) {
  67723. errorHandler("Error in onSuccess callback", e);
  67724. }
  67725. }
  67726. scene._removePendingData(loadingToken);
  67727. };
  67728. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67729. if (plugin.loadAssetContainer) {
  67730. var syncedPlugin = plugin;
  67731. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67732. if (!assetContainer) {
  67733. return;
  67734. }
  67735. scene.loadingPluginName = plugin.name;
  67736. successHandler(assetContainer);
  67737. }
  67738. else if (plugin.loadAssetContainerAsync) {
  67739. var asyncedPlugin = plugin;
  67740. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67741. scene.loadingPluginName = plugin.name;
  67742. successHandler(assetContainer);
  67743. }).catch(function (error) {
  67744. errorHandler(error.message, error);
  67745. });
  67746. }
  67747. else {
  67748. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67749. }
  67750. if (SceneLoader.ShowLoadingScreen) {
  67751. scene.executeWhenReady(function () {
  67752. scene.getEngine().hideLoadingUI();
  67753. });
  67754. }
  67755. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67756. };
  67757. /**
  67758. * Load a scene into an asset container
  67759. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67760. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67761. * @param scene is the instance of BABYLON.Scene to append to
  67762. * @param onProgress a callback with a progress event for each file being loaded
  67763. * @param pluginExtension the extension used to determine the plugin
  67764. * @returns The loaded asset container
  67765. */
  67766. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67767. if (sceneFilename === void 0) { sceneFilename = ""; }
  67768. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67769. if (onProgress === void 0) { onProgress = null; }
  67770. if (pluginExtension === void 0) { pluginExtension = null; }
  67771. return new Promise(function (resolve, reject) {
  67772. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67773. resolve(assetContainer);
  67774. }, onProgress, function (scene, message, exception) {
  67775. reject(exception || new Error(message));
  67776. }, pluginExtension);
  67777. });
  67778. };
  67779. // Flags
  67780. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67781. SceneLoader._ShowLoadingScreen = true;
  67782. SceneLoader._CleanBoneMatrixWeights = false;
  67783. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67784. // Members
  67785. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67786. SceneLoader._registeredPlugins = {};
  67787. return SceneLoader;
  67788. }());
  67789. BABYLON.SceneLoader = SceneLoader;
  67790. ;
  67791. })(BABYLON || (BABYLON = {}));
  67792. //# sourceMappingURL=babylon.sceneLoader.js.map
  67793. var BABYLON;
  67794. (function (BABYLON) {
  67795. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67796. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67797. var parsedMaterial = parsedData.materials[index];
  67798. if (parsedMaterial.id === id) {
  67799. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67800. }
  67801. }
  67802. return null;
  67803. };
  67804. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67805. for (var i in names) {
  67806. if (mesh.name === names[i]) {
  67807. hierarchyIds.push(mesh.id);
  67808. return true;
  67809. }
  67810. }
  67811. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67812. hierarchyIds.push(mesh.id);
  67813. return true;
  67814. }
  67815. return false;
  67816. };
  67817. var logOperation = function (operation, producer) {
  67818. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67819. };
  67820. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67821. if (addToScene === void 0) { addToScene = false; }
  67822. var container = new BABYLON.AssetContainer(scene);
  67823. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67824. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67825. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67826. // and avoid problems with multiple concurrent .babylon loads.
  67827. var log = "importScene has failed JSON parse";
  67828. try {
  67829. var parsedData = JSON.parse(data);
  67830. log = "";
  67831. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67832. var index;
  67833. var cache;
  67834. // Lights
  67835. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67836. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67837. var parsedLight = parsedData.lights[index];
  67838. var light = BABYLON.Light.Parse(parsedLight, scene);
  67839. if (light) {
  67840. container.lights.push(light);
  67841. log += (index === 0 ? "\n\tLights:" : "");
  67842. log += "\n\t\t" + light.toString(fullDetails);
  67843. }
  67844. }
  67845. }
  67846. // Animations
  67847. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67848. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67849. var parsedAnimation = parsedData.animations[index];
  67850. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67851. scene.animations.push(animation);
  67852. container.animations.push(animation);
  67853. log += (index === 0 ? "\n\tAnimations:" : "");
  67854. log += "\n\t\t" + animation.toString(fullDetails);
  67855. }
  67856. }
  67857. // Materials
  67858. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67859. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67860. var parsedMaterial = parsedData.materials[index];
  67861. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67862. container.materials.push(mat);
  67863. log += (index === 0 ? "\n\tMaterials:" : "");
  67864. log += "\n\t\t" + mat.toString(fullDetails);
  67865. }
  67866. }
  67867. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67868. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67869. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67870. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67871. container.multiMaterials.push(mmat);
  67872. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67873. log += "\n\t\t" + mmat.toString(fullDetails);
  67874. }
  67875. }
  67876. // Morph targets
  67877. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67878. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67879. var managerData = _a[_i];
  67880. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67881. }
  67882. }
  67883. // Skeletons
  67884. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67885. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67886. var parsedSkeleton = parsedData.skeletons[index];
  67887. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67888. container.skeletons.push(skeleton);
  67889. log += (index === 0 ? "\n\tSkeletons:" : "");
  67890. log += "\n\t\t" + skeleton.toString(fullDetails);
  67891. }
  67892. }
  67893. // Geometries
  67894. var geometries = parsedData.geometries;
  67895. if (geometries !== undefined && geometries !== null) {
  67896. var addedGeometry = new Array();
  67897. // Boxes
  67898. var boxes = geometries.boxes;
  67899. if (boxes !== undefined && boxes !== null) {
  67900. for (index = 0, cache = boxes.length; index < cache; index++) {
  67901. var parsedBox = boxes[index];
  67902. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67903. }
  67904. }
  67905. // Spheres
  67906. var spheres = geometries.spheres;
  67907. if (spheres !== undefined && spheres !== null) {
  67908. for (index = 0, cache = spheres.length; index < cache; index++) {
  67909. var parsedSphere = spheres[index];
  67910. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67911. }
  67912. }
  67913. // Cylinders
  67914. var cylinders = geometries.cylinders;
  67915. if (cylinders !== undefined && cylinders !== null) {
  67916. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67917. var parsedCylinder = cylinders[index];
  67918. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67919. }
  67920. }
  67921. // Toruses
  67922. var toruses = geometries.toruses;
  67923. if (toruses !== undefined && toruses !== null) {
  67924. for (index = 0, cache = toruses.length; index < cache; index++) {
  67925. var parsedTorus = toruses[index];
  67926. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67927. }
  67928. }
  67929. // Grounds
  67930. var grounds = geometries.grounds;
  67931. if (grounds !== undefined && grounds !== null) {
  67932. for (index = 0, cache = grounds.length; index < cache; index++) {
  67933. var parsedGround = grounds[index];
  67934. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67935. }
  67936. }
  67937. // Planes
  67938. var planes = geometries.planes;
  67939. if (planes !== undefined && planes !== null) {
  67940. for (index = 0, cache = planes.length; index < cache; index++) {
  67941. var parsedPlane = planes[index];
  67942. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67943. }
  67944. }
  67945. // TorusKnots
  67946. var torusKnots = geometries.torusKnots;
  67947. if (torusKnots !== undefined && torusKnots !== null) {
  67948. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67949. var parsedTorusKnot = torusKnots[index];
  67950. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67951. }
  67952. }
  67953. // VertexData
  67954. var vertexData = geometries.vertexData;
  67955. if (vertexData !== undefined && vertexData !== null) {
  67956. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67957. var parsedVertexData = vertexData[index];
  67958. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67959. }
  67960. }
  67961. addedGeometry.forEach(function (g) {
  67962. if (g) {
  67963. container.geometries.push(g);
  67964. }
  67965. });
  67966. }
  67967. // Transform nodes
  67968. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67969. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67970. var parsedTransformNode = parsedData.transformNodes[index];
  67971. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67972. container.transformNodes.push(node);
  67973. }
  67974. }
  67975. // Meshes
  67976. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67977. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67978. var parsedMesh = parsedData.meshes[index];
  67979. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67980. container.meshes.push(mesh);
  67981. log += (index === 0 ? "\n\tMeshes:" : "");
  67982. log += "\n\t\t" + mesh.toString(fullDetails);
  67983. }
  67984. }
  67985. // Cameras
  67986. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67987. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67988. var parsedCamera = parsedData.cameras[index];
  67989. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67990. container.cameras.push(camera);
  67991. log += (index === 0 ? "\n\tCameras:" : "");
  67992. log += "\n\t\t" + camera.toString(fullDetails);
  67993. }
  67994. }
  67995. // Browsing all the graph to connect the dots
  67996. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67997. var camera = scene.cameras[index];
  67998. if (camera._waitingParentId) {
  67999. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68000. camera._waitingParentId = null;
  68001. }
  68002. }
  68003. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68004. var light_1 = scene.lights[index];
  68005. if (light_1 && light_1._waitingParentId) {
  68006. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68007. light_1._waitingParentId = null;
  68008. }
  68009. }
  68010. // Sounds
  68011. // TODO: add sound
  68012. var loadedSounds = [];
  68013. var loadedSound;
  68014. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68015. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68016. var parsedSound = parsedData.sounds[index];
  68017. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68018. if (!parsedSound.url)
  68019. parsedSound.url = parsedSound.name;
  68020. if (!loadedSounds[parsedSound.url]) {
  68021. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68022. loadedSounds[parsedSound.url] = loadedSound;
  68023. container.sounds.push(loadedSound);
  68024. }
  68025. else {
  68026. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68027. }
  68028. }
  68029. else {
  68030. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68031. }
  68032. }
  68033. }
  68034. loadedSounds = [];
  68035. // Connect parents & children and parse actions
  68036. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68037. var transformNode = scene.transformNodes[index];
  68038. if (transformNode._waitingParentId) {
  68039. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68040. transformNode._waitingParentId = null;
  68041. }
  68042. }
  68043. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68044. var mesh = scene.meshes[index];
  68045. if (mesh._waitingParentId) {
  68046. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68047. mesh._waitingParentId = null;
  68048. }
  68049. if (mesh._waitingActions) {
  68050. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68051. mesh._waitingActions = null;
  68052. }
  68053. }
  68054. // freeze world matrix application
  68055. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68056. var currentMesh = scene.meshes[index];
  68057. if (currentMesh._waitingFreezeWorldMatrix) {
  68058. currentMesh.freezeWorldMatrix();
  68059. currentMesh._waitingFreezeWorldMatrix = null;
  68060. }
  68061. else {
  68062. currentMesh.computeWorldMatrix(true);
  68063. }
  68064. }
  68065. // Particles Systems
  68066. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68067. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68068. var parsedParticleSystem = parsedData.particleSystems[index];
  68069. if (parsedParticleSystem.activeParticleCount) {
  68070. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68071. container.particleSystems.push(ps);
  68072. }
  68073. else {
  68074. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68075. container.particleSystems.push(ps);
  68076. }
  68077. }
  68078. }
  68079. // Lens flares
  68080. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68081. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68082. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68083. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68084. container.lensFlareSystems.push(lf);
  68085. }
  68086. }
  68087. // Shadows
  68088. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68089. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68090. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68091. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68092. container.shadowGenerators.push(sg);
  68093. }
  68094. }
  68095. // Lights exclusions / inclusions
  68096. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68097. var light_2 = scene.lights[index];
  68098. // Excluded check
  68099. if (light_2._excludedMeshesIds.length > 0) {
  68100. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68101. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68102. if (excludedMesh) {
  68103. light_2.excludedMeshes.push(excludedMesh);
  68104. }
  68105. }
  68106. light_2._excludedMeshesIds = [];
  68107. }
  68108. // Included check
  68109. if (light_2._includedOnlyMeshesIds.length > 0) {
  68110. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68111. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68112. if (includedOnlyMesh) {
  68113. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68114. }
  68115. }
  68116. light_2._includedOnlyMeshesIds = [];
  68117. }
  68118. }
  68119. // Effect layers
  68120. if (parsedData.effectLayers) {
  68121. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68122. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68123. container.effectLayers.push(effectLayer);
  68124. }
  68125. }
  68126. // Actions (scene)
  68127. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68128. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68129. }
  68130. if (!addToScene) {
  68131. container.removeAllFromScene();
  68132. }
  68133. }
  68134. catch (err) {
  68135. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68136. if (onError) {
  68137. onError(msg, err);
  68138. }
  68139. else {
  68140. BABYLON.Tools.Log(msg);
  68141. throw err;
  68142. }
  68143. }
  68144. finally {
  68145. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68146. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68147. }
  68148. }
  68149. return container;
  68150. };
  68151. BABYLON.SceneLoader.RegisterPlugin({
  68152. name: "babylon.js",
  68153. extensions: ".babylon",
  68154. canDirectLoad: function (data) {
  68155. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68156. return true;
  68157. }
  68158. return false;
  68159. },
  68160. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68161. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68162. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68163. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68164. // and avoid problems with multiple concurrent .babylon loads.
  68165. var log = "importMesh has failed JSON parse";
  68166. try {
  68167. var parsedData = JSON.parse(data);
  68168. log = "";
  68169. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68170. if (!meshesNames) {
  68171. meshesNames = null;
  68172. }
  68173. else if (!Array.isArray(meshesNames)) {
  68174. meshesNames = [meshesNames];
  68175. }
  68176. var hierarchyIds = new Array();
  68177. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68178. var loadedSkeletonsIds = [];
  68179. var loadedMaterialsIds = [];
  68180. var index;
  68181. var cache;
  68182. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68183. var parsedMesh = parsedData.meshes[index];
  68184. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68185. if (meshesNames !== null) {
  68186. // Remove found mesh name from list.
  68187. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68188. }
  68189. //Geometry?
  68190. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68191. //does the file contain geometries?
  68192. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68193. //find the correct geometry and add it to the scene
  68194. var found = false;
  68195. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68196. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68197. return;
  68198. }
  68199. else {
  68200. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68201. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68202. switch (geometryType) {
  68203. case "boxes":
  68204. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68205. break;
  68206. case "spheres":
  68207. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68208. break;
  68209. case "cylinders":
  68210. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68211. break;
  68212. case "toruses":
  68213. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68214. break;
  68215. case "grounds":
  68216. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68217. break;
  68218. case "planes":
  68219. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68220. break;
  68221. case "torusKnots":
  68222. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68223. break;
  68224. case "vertexData":
  68225. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68226. break;
  68227. }
  68228. found = true;
  68229. }
  68230. });
  68231. }
  68232. });
  68233. if (found === false) {
  68234. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68235. }
  68236. }
  68237. }
  68238. // Material ?
  68239. if (parsedMesh.materialId) {
  68240. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68241. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68242. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68243. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68244. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68245. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68246. var subMatId = parsedMultiMaterial.materials[matIndex];
  68247. loadedMaterialsIds.push(subMatId);
  68248. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68249. if (mat) {
  68250. log += "\n\tMaterial " + mat.toString(fullDetails);
  68251. }
  68252. }
  68253. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68254. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68255. if (mmat) {
  68256. materialFound = true;
  68257. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68258. }
  68259. break;
  68260. }
  68261. }
  68262. }
  68263. if (materialFound === false) {
  68264. loadedMaterialsIds.push(parsedMesh.materialId);
  68265. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68266. if (!mat) {
  68267. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68268. }
  68269. else {
  68270. log += "\n\tMaterial " + mat.toString(fullDetails);
  68271. }
  68272. }
  68273. }
  68274. // Skeleton ?
  68275. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68276. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68277. if (skeletonAlreadyLoaded === false) {
  68278. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68279. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68280. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68281. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68282. skeletons.push(skeleton);
  68283. loadedSkeletonsIds.push(parsedSkeleton.id);
  68284. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68285. }
  68286. }
  68287. }
  68288. }
  68289. // Morph targets ?
  68290. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68291. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68292. var managerData = _a[_i];
  68293. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68294. }
  68295. }
  68296. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68297. meshes.push(mesh);
  68298. log += "\n\tMesh " + mesh.toString(fullDetails);
  68299. }
  68300. }
  68301. // Connecting parents
  68302. var currentMesh;
  68303. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68304. currentMesh = scene.meshes[index];
  68305. if (currentMesh._waitingParentId) {
  68306. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68307. currentMesh._waitingParentId = null;
  68308. }
  68309. }
  68310. // freeze and compute world matrix application
  68311. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68312. currentMesh = scene.meshes[index];
  68313. if (currentMesh._waitingFreezeWorldMatrix) {
  68314. currentMesh.freezeWorldMatrix();
  68315. currentMesh._waitingFreezeWorldMatrix = null;
  68316. }
  68317. else {
  68318. currentMesh.computeWorldMatrix(true);
  68319. }
  68320. }
  68321. }
  68322. // Particles
  68323. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68324. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68325. var parsedParticleSystem = parsedData.particleSystems[index];
  68326. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68327. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68328. }
  68329. }
  68330. }
  68331. return true;
  68332. }
  68333. catch (err) {
  68334. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68335. if (onError) {
  68336. onError(msg, err);
  68337. }
  68338. else {
  68339. BABYLON.Tools.Log(msg);
  68340. throw err;
  68341. }
  68342. }
  68343. finally {
  68344. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68345. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68346. }
  68347. }
  68348. return false;
  68349. },
  68350. load: function (scene, data, rootUrl, onError) {
  68351. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68352. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68353. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68354. // and avoid problems with multiple concurrent .babylon loads.
  68355. var log = "importScene has failed JSON parse";
  68356. try {
  68357. var parsedData = JSON.parse(data);
  68358. log = "";
  68359. // Scene
  68360. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68361. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68362. }
  68363. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68364. scene.autoClear = parsedData.autoClear;
  68365. }
  68366. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68367. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68368. }
  68369. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68370. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68371. }
  68372. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68373. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68374. }
  68375. // Fog
  68376. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68377. scene.fogMode = parsedData.fogMode;
  68378. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68379. scene.fogStart = parsedData.fogStart;
  68380. scene.fogEnd = parsedData.fogEnd;
  68381. scene.fogDensity = parsedData.fogDensity;
  68382. log += "\tFog mode for scene: ";
  68383. switch (scene.fogMode) {
  68384. // getters not compiling, so using hardcoded
  68385. case 1:
  68386. log += "exp\n";
  68387. break;
  68388. case 2:
  68389. log += "exp2\n";
  68390. break;
  68391. case 3:
  68392. log += "linear\n";
  68393. break;
  68394. }
  68395. }
  68396. //Physics
  68397. if (parsedData.physicsEnabled) {
  68398. var physicsPlugin;
  68399. if (parsedData.physicsEngine === "cannon") {
  68400. physicsPlugin = new BABYLON.CannonJSPlugin();
  68401. }
  68402. else if (parsedData.physicsEngine === "oimo") {
  68403. physicsPlugin = new BABYLON.OimoJSPlugin();
  68404. }
  68405. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68406. //else - default engine, which is currently oimo
  68407. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68408. scene.enablePhysics(physicsGravity, physicsPlugin);
  68409. }
  68410. // Metadata
  68411. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68412. scene.metadata = parsedData.metadata;
  68413. }
  68414. //collisions, if defined. otherwise, default is true
  68415. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68416. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68417. }
  68418. scene.workerCollisions = !!parsedData.workerCollisions;
  68419. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68420. if (!container) {
  68421. return false;
  68422. }
  68423. if (parsedData.autoAnimate) {
  68424. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68425. }
  68426. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68427. scene.setActiveCameraByID(parsedData.activeCameraID);
  68428. }
  68429. // Environment texture
  68430. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68431. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68432. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68433. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68434. if (parsedData.environmentTextureRotationY) {
  68435. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68436. }
  68437. scene.environmentTexture = hdrTexture;
  68438. }
  68439. else {
  68440. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68441. if (parsedData.environmentTextureRotationY) {
  68442. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68443. }
  68444. scene.environmentTexture = cubeTexture;
  68445. }
  68446. if (parsedData.createDefaultSkybox === true) {
  68447. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68448. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68449. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68450. }
  68451. }
  68452. // Finish
  68453. return true;
  68454. }
  68455. catch (err) {
  68456. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68457. if (onError) {
  68458. onError(msg, err);
  68459. }
  68460. else {
  68461. BABYLON.Tools.Log(msg);
  68462. throw err;
  68463. }
  68464. }
  68465. finally {
  68466. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68467. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68468. }
  68469. }
  68470. return false;
  68471. },
  68472. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68473. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68474. return container;
  68475. }
  68476. });
  68477. })(BABYLON || (BABYLON = {}));
  68478. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68479. var BABYLON;
  68480. (function (BABYLON) {
  68481. var FilesInput = /** @class */ (function () {
  68482. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68483. this.onProcessFileCallback = function () { return true; };
  68484. this._engine = engine;
  68485. this._currentScene = scene;
  68486. this._sceneLoadedCallback = sceneLoadedCallback;
  68487. this._progressCallback = progressCallback;
  68488. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68489. this._textureLoadingCallback = textureLoadingCallback;
  68490. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68491. this._onReloadCallback = onReloadCallback;
  68492. this._errorCallback = errorCallback;
  68493. }
  68494. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68495. var _this = this;
  68496. if (elementToMonitor) {
  68497. this._elementToMonitor = elementToMonitor;
  68498. this._dragEnterHandler = function (e) { _this.drag(e); };
  68499. this._dragOverHandler = function (e) { _this.drag(e); };
  68500. this._dropHandler = function (e) { _this.drop(e); };
  68501. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68502. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68503. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68504. }
  68505. };
  68506. FilesInput.prototype.dispose = function () {
  68507. if (!this._elementToMonitor) {
  68508. return;
  68509. }
  68510. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68511. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68512. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68513. };
  68514. FilesInput.prototype.renderFunction = function () {
  68515. if (this._additionalRenderLoopLogicCallback) {
  68516. this._additionalRenderLoopLogicCallback();
  68517. }
  68518. if (this._currentScene) {
  68519. if (this._textureLoadingCallback) {
  68520. var remaining = this._currentScene.getWaitingItemsCount();
  68521. if (remaining > 0) {
  68522. this._textureLoadingCallback(remaining);
  68523. }
  68524. }
  68525. this._currentScene.render();
  68526. }
  68527. };
  68528. FilesInput.prototype.drag = function (e) {
  68529. e.stopPropagation();
  68530. e.preventDefault();
  68531. };
  68532. FilesInput.prototype.drop = function (eventDrop) {
  68533. eventDrop.stopPropagation();
  68534. eventDrop.preventDefault();
  68535. this.loadFiles(eventDrop);
  68536. };
  68537. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68538. var _this = this;
  68539. var reader = folder.createReader();
  68540. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68541. reader.readEntries(function (entries) {
  68542. remaining.count += entries.length;
  68543. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68544. var entry = entries_1[_i];
  68545. if (entry.isFile) {
  68546. entry.file(function (file) {
  68547. file.correctName = relativePath + file.name;
  68548. files.push(file);
  68549. if (--remaining.count === 0) {
  68550. callback();
  68551. }
  68552. });
  68553. }
  68554. else if (entry.isDirectory) {
  68555. _this._traverseFolder(entry, files, remaining, callback);
  68556. }
  68557. }
  68558. if (--remaining.count) {
  68559. callback();
  68560. }
  68561. });
  68562. };
  68563. FilesInput.prototype._processFiles = function (files) {
  68564. for (var i = 0; i < files.length; i++) {
  68565. var name = files[i].correctName.toLowerCase();
  68566. var extension = name.split('.').pop();
  68567. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68568. continue;
  68569. }
  68570. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68571. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68572. this._sceneFileToLoad = files[i];
  68573. }
  68574. else {
  68575. FilesInput.FilesToLoad[name] = files[i];
  68576. }
  68577. }
  68578. };
  68579. FilesInput.prototype.loadFiles = function (event) {
  68580. var _this = this;
  68581. if (this._startingProcessingFilesCallback)
  68582. this._startingProcessingFilesCallback();
  68583. // Handling data transfer via drag'n'drop
  68584. if (event && event.dataTransfer && event.dataTransfer.files) {
  68585. this._filesToLoad = event.dataTransfer.files;
  68586. }
  68587. // Handling files from input files
  68588. if (event && event.target && event.target.files) {
  68589. this._filesToLoad = event.target.files;
  68590. }
  68591. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68592. var files_1 = new Array();
  68593. var folders = [];
  68594. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68595. for (var i = 0; i < this._filesToLoad.length; i++) {
  68596. var fileToLoad = this._filesToLoad[i];
  68597. var name_1 = fileToLoad.name.toLowerCase();
  68598. var entry = void 0;
  68599. fileToLoad.correctName = name_1;
  68600. if (items) {
  68601. var item = items[i];
  68602. if (item.getAsEntry) {
  68603. entry = item.getAsEntry();
  68604. }
  68605. else if (item.webkitGetAsEntry) {
  68606. entry = item.webkitGetAsEntry();
  68607. }
  68608. }
  68609. if (!entry) {
  68610. files_1.push(fileToLoad);
  68611. }
  68612. else {
  68613. if (entry.isDirectory) {
  68614. folders.push(entry);
  68615. }
  68616. else {
  68617. files_1.push(fileToLoad);
  68618. }
  68619. }
  68620. }
  68621. if (folders.length === 0) {
  68622. this._processFiles(files_1);
  68623. this._processReload();
  68624. }
  68625. else {
  68626. var remaining = { count: folders.length };
  68627. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68628. var folder = folders_1[_i];
  68629. this._traverseFolder(folder, files_1, remaining, function () {
  68630. _this._processFiles(files_1);
  68631. if (remaining.count === 0) {
  68632. _this._processReload();
  68633. }
  68634. });
  68635. }
  68636. }
  68637. }
  68638. };
  68639. FilesInput.prototype._processReload = function () {
  68640. if (this._onReloadCallback) {
  68641. this._onReloadCallback(this._sceneFileToLoad);
  68642. }
  68643. else {
  68644. this.reload();
  68645. }
  68646. };
  68647. FilesInput.prototype.reload = function () {
  68648. var _this = this;
  68649. // If a scene file has been provided
  68650. if (this._sceneFileToLoad) {
  68651. if (this._currentScene) {
  68652. if (BABYLON.Tools.errorsCount > 0) {
  68653. BABYLON.Tools.ClearLogCache();
  68654. }
  68655. this._engine.stopRenderLoop();
  68656. }
  68657. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68658. if (_this._progressCallback) {
  68659. _this._progressCallback(progress);
  68660. }
  68661. }).then(function (scene) {
  68662. if (_this._currentScene) {
  68663. _this._currentScene.dispose();
  68664. }
  68665. _this._currentScene = scene;
  68666. if (_this._sceneLoadedCallback) {
  68667. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68668. }
  68669. // Wait for textures and shaders to be ready
  68670. _this._currentScene.executeWhenReady(function () {
  68671. _this._engine.runRenderLoop(function () {
  68672. _this.renderFunction();
  68673. });
  68674. });
  68675. }).catch(function (error) {
  68676. if (_this._errorCallback) {
  68677. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68678. }
  68679. });
  68680. }
  68681. else {
  68682. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68683. }
  68684. };
  68685. FilesInput.FilesToLoad = {};
  68686. return FilesInput;
  68687. }());
  68688. BABYLON.FilesInput = FilesInput;
  68689. })(BABYLON || (BABYLON = {}));
  68690. //# sourceMappingURL=babylon.filesInput.js.map
  68691. var BABYLON;
  68692. (function (BABYLON) {
  68693. /**
  68694. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68695. * The underlying implementation relies on an associative array to ensure the best performances.
  68696. * The value can be anything including 'null' but except 'undefined'
  68697. */
  68698. var StringDictionary = /** @class */ (function () {
  68699. function StringDictionary() {
  68700. this._count = 0;
  68701. this._data = {};
  68702. }
  68703. /**
  68704. * This will clear this dictionary and copy the content from the 'source' one.
  68705. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68706. * @param source the dictionary to take the content from and copy to this dictionary
  68707. */
  68708. StringDictionary.prototype.copyFrom = function (source) {
  68709. var _this = this;
  68710. this.clear();
  68711. source.forEach(function (t, v) { return _this.add(t, v); });
  68712. };
  68713. /**
  68714. * Get a value based from its key
  68715. * @param key the given key to get the matching value from
  68716. * @return the value if found, otherwise undefined is returned
  68717. */
  68718. StringDictionary.prototype.get = function (key) {
  68719. var val = this._data[key];
  68720. if (val !== undefined) {
  68721. return val;
  68722. }
  68723. return undefined;
  68724. };
  68725. /**
  68726. * Get a value from its key or add it if it doesn't exist.
  68727. * This method will ensure you that a given key/data will be present in the dictionary.
  68728. * @param key the given key to get the matching value from
  68729. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68730. * The factory will only be invoked if there's no data for the given key.
  68731. * @return the value corresponding to the key.
  68732. */
  68733. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68734. var val = this.get(key);
  68735. if (val !== undefined) {
  68736. return val;
  68737. }
  68738. val = factory(key);
  68739. if (val) {
  68740. this.add(key, val);
  68741. }
  68742. return val;
  68743. };
  68744. /**
  68745. * Get a value from its key if present in the dictionary otherwise add it
  68746. * @param key the key to get the value from
  68747. * @param val if there's no such key/value pair in the dictionary add it with this value
  68748. * @return the value corresponding to the key
  68749. */
  68750. StringDictionary.prototype.getOrAdd = function (key, val) {
  68751. var curVal = this.get(key);
  68752. if (curVal !== undefined) {
  68753. return curVal;
  68754. }
  68755. this.add(key, val);
  68756. return val;
  68757. };
  68758. /**
  68759. * Check if there's a given key in the dictionary
  68760. * @param key the key to check for
  68761. * @return true if the key is present, false otherwise
  68762. */
  68763. StringDictionary.prototype.contains = function (key) {
  68764. return this._data[key] !== undefined;
  68765. };
  68766. /**
  68767. * Add a new key and its corresponding value
  68768. * @param key the key to add
  68769. * @param value the value corresponding to the key
  68770. * @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
  68771. */
  68772. StringDictionary.prototype.add = function (key, value) {
  68773. if (this._data[key] !== undefined) {
  68774. return false;
  68775. }
  68776. this._data[key] = value;
  68777. ++this._count;
  68778. return true;
  68779. };
  68780. StringDictionary.prototype.set = function (key, value) {
  68781. if (this._data[key] === undefined) {
  68782. return false;
  68783. }
  68784. this._data[key] = value;
  68785. return true;
  68786. };
  68787. /**
  68788. * Get the element of the given key and remove it from the dictionary
  68789. * @param key
  68790. */
  68791. StringDictionary.prototype.getAndRemove = function (key) {
  68792. var val = this.get(key);
  68793. if (val !== undefined) {
  68794. delete this._data[key];
  68795. --this._count;
  68796. return val;
  68797. }
  68798. return null;
  68799. };
  68800. /**
  68801. * Remove a key/value from the dictionary.
  68802. * @param key the key to remove
  68803. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68804. */
  68805. StringDictionary.prototype.remove = function (key) {
  68806. if (this.contains(key)) {
  68807. delete this._data[key];
  68808. --this._count;
  68809. return true;
  68810. }
  68811. return false;
  68812. };
  68813. /**
  68814. * Clear the whole content of the dictionary
  68815. */
  68816. StringDictionary.prototype.clear = function () {
  68817. this._data = {};
  68818. this._count = 0;
  68819. };
  68820. Object.defineProperty(StringDictionary.prototype, "count", {
  68821. get: function () {
  68822. return this._count;
  68823. },
  68824. enumerable: true,
  68825. configurable: true
  68826. });
  68827. /**
  68828. * Execute a callback on each key/val of the dictionary.
  68829. * Note that you can remove any element in this dictionary in the callback implementation
  68830. * @param callback the callback to execute on a given key/value pair
  68831. */
  68832. StringDictionary.prototype.forEach = function (callback) {
  68833. for (var cur in this._data) {
  68834. var val = this._data[cur];
  68835. callback(cur, val);
  68836. }
  68837. };
  68838. /**
  68839. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68840. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68841. * Note that you can remove any element in this dictionary in the callback implementation
  68842. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68843. */
  68844. StringDictionary.prototype.first = function (callback) {
  68845. for (var cur in this._data) {
  68846. var val = this._data[cur];
  68847. var res = callback(cur, val);
  68848. if (res) {
  68849. return res;
  68850. }
  68851. }
  68852. return null;
  68853. };
  68854. return StringDictionary;
  68855. }());
  68856. BABYLON.StringDictionary = StringDictionary;
  68857. })(BABYLON || (BABYLON = {}));
  68858. //# sourceMappingURL=babylon.stringDictionary.js.map
  68859. var BABYLON;
  68860. (function (BABYLON) {
  68861. var Tags = /** @class */ (function () {
  68862. function Tags() {
  68863. }
  68864. Tags.EnableFor = function (obj) {
  68865. obj._tags = obj._tags || {};
  68866. obj.hasTags = function () {
  68867. return Tags.HasTags(obj);
  68868. };
  68869. obj.addTags = function (tagsString) {
  68870. return Tags.AddTagsTo(obj, tagsString);
  68871. };
  68872. obj.removeTags = function (tagsString) {
  68873. return Tags.RemoveTagsFrom(obj, tagsString);
  68874. };
  68875. obj.matchesTagsQuery = function (tagsQuery) {
  68876. return Tags.MatchesQuery(obj, tagsQuery);
  68877. };
  68878. };
  68879. Tags.DisableFor = function (obj) {
  68880. delete obj._tags;
  68881. delete obj.hasTags;
  68882. delete obj.addTags;
  68883. delete obj.removeTags;
  68884. delete obj.matchesTagsQuery;
  68885. };
  68886. Tags.HasTags = function (obj) {
  68887. if (!obj._tags) {
  68888. return false;
  68889. }
  68890. return !BABYLON.Tools.IsEmpty(obj._tags);
  68891. };
  68892. Tags.GetTags = function (obj, asString) {
  68893. if (asString === void 0) { asString = true; }
  68894. if (!obj._tags) {
  68895. return null;
  68896. }
  68897. if (asString) {
  68898. var tagsArray = [];
  68899. for (var tag in obj._tags) {
  68900. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68901. tagsArray.push(tag);
  68902. }
  68903. }
  68904. return tagsArray.join(" ");
  68905. }
  68906. else {
  68907. return obj._tags;
  68908. }
  68909. };
  68910. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68911. // a tag cannot start with '||', '&&', and '!'
  68912. // it cannot contain whitespaces
  68913. Tags.AddTagsTo = function (obj, tagsString) {
  68914. if (!tagsString) {
  68915. return;
  68916. }
  68917. if (typeof tagsString !== "string") {
  68918. return;
  68919. }
  68920. var tags = tagsString.split(" ");
  68921. tags.forEach(function (tag, index, array) {
  68922. Tags._AddTagTo(obj, tag);
  68923. });
  68924. };
  68925. Tags._AddTagTo = function (obj, tag) {
  68926. tag = tag.trim();
  68927. if (tag === "" || tag === "true" || tag === "false") {
  68928. return;
  68929. }
  68930. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68931. return;
  68932. }
  68933. Tags.EnableFor(obj);
  68934. obj._tags[tag] = true;
  68935. };
  68936. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68937. if (!Tags.HasTags(obj)) {
  68938. return;
  68939. }
  68940. var tags = tagsString.split(" ");
  68941. for (var t in tags) {
  68942. Tags._RemoveTagFrom(obj, tags[t]);
  68943. }
  68944. };
  68945. Tags._RemoveTagFrom = function (obj, tag) {
  68946. delete obj._tags[tag];
  68947. };
  68948. Tags.MatchesQuery = function (obj, tagsQuery) {
  68949. if (tagsQuery === undefined) {
  68950. return true;
  68951. }
  68952. if (tagsQuery === "") {
  68953. return Tags.HasTags(obj);
  68954. }
  68955. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68956. };
  68957. return Tags;
  68958. }());
  68959. BABYLON.Tags = Tags;
  68960. })(BABYLON || (BABYLON = {}));
  68961. //# sourceMappingURL=babylon.tags.js.map
  68962. var BABYLON;
  68963. (function (BABYLON) {
  68964. /**
  68965. * Class used to evalaute queries containing `and` and `or` operators
  68966. */
  68967. var AndOrNotEvaluator = /** @class */ (function () {
  68968. function AndOrNotEvaluator() {
  68969. }
  68970. /**
  68971. * Evaluate a query
  68972. * @param query defines the query to evaluate
  68973. * @param evaluateCallback defines the callback used to filter result
  68974. * @returns true if the query matches
  68975. */
  68976. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68977. if (!query.match(/\([^\(\)]*\)/g)) {
  68978. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68979. }
  68980. else {
  68981. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68982. // remove parenthesis
  68983. r = r.slice(1, r.length - 1);
  68984. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68985. });
  68986. }
  68987. if (query === "true") {
  68988. return true;
  68989. }
  68990. if (query === "false") {
  68991. return false;
  68992. }
  68993. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68994. };
  68995. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68996. evaluateCallback = evaluateCallback || (function (r) {
  68997. return r === "true" ? true : false;
  68998. });
  68999. var result;
  69000. var or = parenthesisContent.split("||");
  69001. for (var i in or) {
  69002. if (or.hasOwnProperty(i)) {
  69003. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69004. var and = ori.split("&&");
  69005. if (and.length > 1) {
  69006. for (var j = 0; j < and.length; ++j) {
  69007. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69008. if (andj !== "true" && andj !== "false") {
  69009. if (andj[0] === "!") {
  69010. result = !evaluateCallback(andj.substring(1));
  69011. }
  69012. else {
  69013. result = evaluateCallback(andj);
  69014. }
  69015. }
  69016. else {
  69017. result = andj === "true" ? true : false;
  69018. }
  69019. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69020. ori = "false";
  69021. break;
  69022. }
  69023. }
  69024. }
  69025. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69026. result = true;
  69027. break;
  69028. }
  69029. // result equals false (or undefined)
  69030. if (ori !== "true" && ori !== "false") {
  69031. if (ori[0] === "!") {
  69032. result = !evaluateCallback(ori.substring(1));
  69033. }
  69034. else {
  69035. result = evaluateCallback(ori);
  69036. }
  69037. }
  69038. else {
  69039. result = ori === "true" ? true : false;
  69040. }
  69041. }
  69042. }
  69043. // the whole parenthesis scope is replaced by 'true' or 'false'
  69044. return result ? "true" : "false";
  69045. };
  69046. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69047. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69048. // remove whitespaces
  69049. r = r.replace(/[\s]/g, function () { return ""; });
  69050. return r.length % 2 ? "!" : "";
  69051. });
  69052. booleanString = booleanString.trim();
  69053. if (booleanString === "!true") {
  69054. booleanString = "false";
  69055. }
  69056. else if (booleanString === "!false") {
  69057. booleanString = "true";
  69058. }
  69059. return booleanString;
  69060. };
  69061. return AndOrNotEvaluator;
  69062. }());
  69063. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69064. })(BABYLON || (BABYLON = {}));
  69065. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69066. var BABYLON;
  69067. (function (BABYLON) {
  69068. /**
  69069. * Class used to enable access to IndexedDB
  69070. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69071. */
  69072. var Database = /** @class */ (function () {
  69073. /**
  69074. * Creates a new Database
  69075. * @param urlToScene defines the url to load the scene
  69076. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69077. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69078. */
  69079. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69080. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69081. var _this = this;
  69082. // Handling various flavors of prefixed version of IndexedDB
  69083. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69084. this.callbackManifestChecked = callbackManifestChecked;
  69085. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69086. this.db = null;
  69087. this._enableSceneOffline = false;
  69088. this._enableTexturesOffline = false;
  69089. this.manifestVersionFound = 0;
  69090. this.mustUpdateRessources = false;
  69091. this.hasReachedQuota = false;
  69092. if (!Database.IDBStorageEnabled) {
  69093. this.callbackManifestChecked(true);
  69094. }
  69095. else {
  69096. if (disableManifestCheck) {
  69097. this._enableSceneOffline = true;
  69098. this._enableTexturesOffline = true;
  69099. this.manifestVersionFound = 1;
  69100. BABYLON.Tools.SetImmediate(function () {
  69101. _this.callbackManifestChecked(true);
  69102. });
  69103. }
  69104. else {
  69105. this._checkManifestFile();
  69106. }
  69107. }
  69108. }
  69109. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69110. /**
  69111. * Gets a boolean indicating if scene must be saved in the database
  69112. */
  69113. get: function () {
  69114. return this._enableSceneOffline;
  69115. },
  69116. enumerable: true,
  69117. configurable: true
  69118. });
  69119. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69120. /**
  69121. * Gets a boolean indicating if textures must be saved in the database
  69122. */
  69123. get: function () {
  69124. return this._enableTexturesOffline;
  69125. },
  69126. enumerable: true,
  69127. configurable: true
  69128. });
  69129. Database.prototype._checkManifestFile = function () {
  69130. var _this = this;
  69131. var noManifestFile = function () {
  69132. _this._enableSceneOffline = false;
  69133. _this._enableTexturesOffline = false;
  69134. _this.callbackManifestChecked(false);
  69135. };
  69136. var timeStampUsed = false;
  69137. var manifestURL = this.currentSceneUrl + ".manifest";
  69138. var xhr = new XMLHttpRequest();
  69139. if (navigator.onLine) {
  69140. // Adding a timestamp to by-pass browsers' cache
  69141. timeStampUsed = true;
  69142. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69143. }
  69144. xhr.open("GET", manifestURL, true);
  69145. xhr.addEventListener("load", function () {
  69146. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69147. try {
  69148. var manifestFile = JSON.parse(xhr.response);
  69149. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69150. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69151. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69152. _this.manifestVersionFound = manifestFile.version;
  69153. }
  69154. if (_this.callbackManifestChecked) {
  69155. _this.callbackManifestChecked(true);
  69156. }
  69157. }
  69158. catch (ex) {
  69159. noManifestFile();
  69160. }
  69161. }
  69162. else {
  69163. noManifestFile();
  69164. }
  69165. }, false);
  69166. xhr.addEventListener("error", function (event) {
  69167. if (timeStampUsed) {
  69168. timeStampUsed = false;
  69169. // Let's retry without the timeStamp
  69170. // It could fail when coupled with HTML5 Offline API
  69171. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69172. xhr.open("GET", retryManifestURL, true);
  69173. xhr.send();
  69174. }
  69175. else {
  69176. noManifestFile();
  69177. }
  69178. }, false);
  69179. try {
  69180. xhr.send();
  69181. }
  69182. catch (ex) {
  69183. BABYLON.Tools.Error("Error on XHR send request.");
  69184. this.callbackManifestChecked(false);
  69185. }
  69186. };
  69187. /**
  69188. * Open the database and make it available
  69189. * @param successCallback defines the callback to call on success
  69190. * @param errorCallback defines the callback to call on error
  69191. */
  69192. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69193. var _this = this;
  69194. var handleError = function () {
  69195. _this.isSupported = false;
  69196. if (errorCallback)
  69197. errorCallback();
  69198. };
  69199. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69200. // Your browser doesn't support IndexedDB
  69201. this.isSupported = false;
  69202. if (errorCallback)
  69203. errorCallback();
  69204. }
  69205. else {
  69206. // If the DB hasn't been opened or created yet
  69207. if (!this.db) {
  69208. this.hasReachedQuota = false;
  69209. this.isSupported = true;
  69210. var request = this.idbFactory.open("babylonjs", 1);
  69211. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69212. request.onerror = function (event) {
  69213. handleError();
  69214. };
  69215. // executes when a version change transaction cannot complete due to other active transactions
  69216. request.onblocked = function (event) {
  69217. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69218. handleError();
  69219. };
  69220. // DB has been opened successfully
  69221. request.onsuccess = function (event) {
  69222. _this.db = request.result;
  69223. successCallback();
  69224. };
  69225. // Initialization of the DB. Creating Scenes & Textures stores
  69226. request.onupgradeneeded = function (event) {
  69227. _this.db = (event.target).result;
  69228. if (_this.db) {
  69229. try {
  69230. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69231. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69232. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69233. }
  69234. catch (ex) {
  69235. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69236. handleError();
  69237. }
  69238. }
  69239. };
  69240. }
  69241. // DB has already been created and opened
  69242. else {
  69243. if (successCallback)
  69244. successCallback();
  69245. }
  69246. }
  69247. };
  69248. /**
  69249. * Loads an image from the database
  69250. * @param url defines the url to load from
  69251. * @param image defines the target DOM image
  69252. */
  69253. Database.prototype.loadImageFromDB = function (url, image) {
  69254. var _this = this;
  69255. var completeURL = Database._ReturnFullUrlLocation(url);
  69256. var saveAndLoadImage = function () {
  69257. if (!_this.hasReachedQuota && _this.db !== null) {
  69258. // the texture is not yet in the DB, let's try to save it
  69259. _this._saveImageIntoDBAsync(completeURL, image);
  69260. }
  69261. // If the texture is not in the DB and we've reached the DB quota limit
  69262. // let's load it directly from the web
  69263. else {
  69264. image.src = url;
  69265. }
  69266. };
  69267. if (!this.mustUpdateRessources) {
  69268. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69269. }
  69270. // First time we're download the images or update requested in the manifest file by a version change
  69271. else {
  69272. saveAndLoadImage();
  69273. }
  69274. };
  69275. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69276. if (this.isSupported && this.db !== null) {
  69277. var texture;
  69278. var transaction = this.db.transaction(["textures"]);
  69279. transaction.onabort = function (event) {
  69280. image.src = url;
  69281. };
  69282. transaction.oncomplete = function (event) {
  69283. var blobTextureURL;
  69284. if (texture) {
  69285. var URL = window.URL || window.webkitURL;
  69286. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69287. image.onerror = function () {
  69288. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69289. image.src = url;
  69290. };
  69291. image.src = blobTextureURL;
  69292. }
  69293. else {
  69294. notInDBCallback();
  69295. }
  69296. };
  69297. var getRequest = transaction.objectStore("textures").get(url);
  69298. getRequest.onsuccess = function (event) {
  69299. texture = (event.target).result;
  69300. };
  69301. getRequest.onerror = function (event) {
  69302. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69303. image.src = url;
  69304. };
  69305. }
  69306. else {
  69307. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69308. image.src = url;
  69309. }
  69310. };
  69311. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69312. var _this = this;
  69313. if (this.isSupported) {
  69314. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69315. var generateBlobUrl = function () {
  69316. var blobTextureURL;
  69317. if (blob) {
  69318. var URL = window.URL || window.webkitURL;
  69319. try {
  69320. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69321. }
  69322. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69323. catch (ex) {
  69324. blobTextureURL = URL.createObjectURL(blob);
  69325. }
  69326. }
  69327. if (blobTextureURL) {
  69328. image.src = blobTextureURL;
  69329. }
  69330. };
  69331. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69332. var xhr = new XMLHttpRequest(), blob;
  69333. xhr.open("GET", url, true);
  69334. xhr.responseType = "blob";
  69335. xhr.addEventListener("load", function () {
  69336. if (xhr.status === 200 && _this.db) {
  69337. // Blob as response (XHR2)
  69338. blob = xhr.response;
  69339. var transaction = _this.db.transaction(["textures"], "readwrite");
  69340. // the transaction could abort because of a QuotaExceededError error
  69341. transaction.onabort = function (event) {
  69342. try {
  69343. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69344. var srcElement = (event.srcElement || event.target);
  69345. var error = srcElement.error;
  69346. if (error && error.name === "QuotaExceededError") {
  69347. _this.hasReachedQuota = true;
  69348. }
  69349. }
  69350. catch (ex) { }
  69351. generateBlobUrl();
  69352. };
  69353. transaction.oncomplete = function (event) {
  69354. generateBlobUrl();
  69355. };
  69356. var newTexture = { textureUrl: url, data: blob };
  69357. try {
  69358. // Put the blob into the dabase
  69359. var addRequest = transaction.objectStore("textures").put(newTexture);
  69360. addRequest.onsuccess = function (event) {
  69361. };
  69362. addRequest.onerror = function (event) {
  69363. generateBlobUrl();
  69364. };
  69365. }
  69366. catch (ex) {
  69367. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69368. if (ex.code === 25) {
  69369. Database.IsUASupportingBlobStorage = false;
  69370. }
  69371. image.src = url;
  69372. }
  69373. }
  69374. else {
  69375. image.src = url;
  69376. }
  69377. }, false);
  69378. xhr.addEventListener("error", function (event) {
  69379. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69380. image.src = url;
  69381. }, false);
  69382. xhr.send();
  69383. }
  69384. else {
  69385. image.src = url;
  69386. }
  69387. }
  69388. else {
  69389. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69390. image.src = url;
  69391. }
  69392. };
  69393. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69394. var _this = this;
  69395. var updateVersion = function () {
  69396. // the version is not yet in the DB or we need to update it
  69397. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69398. };
  69399. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69400. };
  69401. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69402. var _this = this;
  69403. if (this.isSupported && this.db) {
  69404. var version;
  69405. try {
  69406. var transaction = this.db.transaction(["versions"]);
  69407. transaction.oncomplete = function (event) {
  69408. if (version) {
  69409. // If the version in the JSON file is different from the version in DB
  69410. if (_this.manifestVersionFound !== version.data) {
  69411. _this.mustUpdateRessources = true;
  69412. updateInDBCallback();
  69413. }
  69414. else {
  69415. callback(version.data);
  69416. }
  69417. }
  69418. // version was not found in DB
  69419. else {
  69420. _this.mustUpdateRessources = true;
  69421. updateInDBCallback();
  69422. }
  69423. };
  69424. transaction.onabort = function (event) {
  69425. callback(-1);
  69426. };
  69427. var getRequest = transaction.objectStore("versions").get(url);
  69428. getRequest.onsuccess = function (event) {
  69429. version = (event.target).result;
  69430. };
  69431. getRequest.onerror = function (event) {
  69432. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69433. callback(-1);
  69434. };
  69435. }
  69436. catch (ex) {
  69437. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69438. callback(-1);
  69439. }
  69440. }
  69441. else {
  69442. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69443. callback(-1);
  69444. }
  69445. };
  69446. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69447. var _this = this;
  69448. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69449. try {
  69450. // Open a transaction to the database
  69451. var transaction = this.db.transaction(["versions"], "readwrite");
  69452. // the transaction could abort because of a QuotaExceededError error
  69453. transaction.onabort = function (event) {
  69454. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69455. var error = event.srcElement['error'];
  69456. if (error && error.name === "QuotaExceededError") {
  69457. _this.hasReachedQuota = true;
  69458. }
  69459. }
  69460. catch (ex) { }
  69461. callback(-1);
  69462. };
  69463. transaction.oncomplete = function (event) {
  69464. callback(_this.manifestVersionFound);
  69465. };
  69466. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69467. // Put the scene into the database
  69468. var addRequest = transaction.objectStore("versions").put(newVersion);
  69469. addRequest.onsuccess = function (event) {
  69470. };
  69471. addRequest.onerror = function (event) {
  69472. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69473. };
  69474. }
  69475. catch (ex) {
  69476. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69477. callback(-1);
  69478. }
  69479. }
  69480. else {
  69481. callback(-1);
  69482. }
  69483. };
  69484. /**
  69485. * Loads a file from database
  69486. * @param url defines the URL to load from
  69487. * @param sceneLoaded defines a callback to call on success
  69488. * @param progressCallBack defines a callback to call when progress changed
  69489. * @param errorCallback defines a callback to call on error
  69490. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69491. */
  69492. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69493. var _this = this;
  69494. var completeUrl = Database._ReturnFullUrlLocation(url);
  69495. var saveAndLoadFile = function () {
  69496. // the scene is not yet in the DB, let's try to save it
  69497. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69498. };
  69499. this._checkVersionFromDB(completeUrl, function (version) {
  69500. if (version !== -1) {
  69501. if (!_this.mustUpdateRessources) {
  69502. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69503. }
  69504. else {
  69505. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69506. }
  69507. }
  69508. else {
  69509. if (errorCallback) {
  69510. errorCallback();
  69511. }
  69512. }
  69513. });
  69514. };
  69515. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69516. if (this.isSupported && this.db) {
  69517. var targetStore;
  69518. if (url.indexOf(".babylon") !== -1) {
  69519. targetStore = "scenes";
  69520. }
  69521. else {
  69522. targetStore = "textures";
  69523. }
  69524. var file;
  69525. var transaction = this.db.transaction([targetStore]);
  69526. transaction.oncomplete = function (event) {
  69527. if (file) {
  69528. callback(file.data);
  69529. }
  69530. // file was not found in DB
  69531. else {
  69532. notInDBCallback();
  69533. }
  69534. };
  69535. transaction.onabort = function (event) {
  69536. notInDBCallback();
  69537. };
  69538. var getRequest = transaction.objectStore(targetStore).get(url);
  69539. getRequest.onsuccess = function (event) {
  69540. file = (event.target).result;
  69541. };
  69542. getRequest.onerror = function (event) {
  69543. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69544. notInDBCallback();
  69545. };
  69546. }
  69547. else {
  69548. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69549. callback();
  69550. }
  69551. };
  69552. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69553. var _this = this;
  69554. if (this.isSupported) {
  69555. var targetStore;
  69556. if (url.indexOf(".babylon") !== -1) {
  69557. targetStore = "scenes";
  69558. }
  69559. else {
  69560. targetStore = "textures";
  69561. }
  69562. // Create XHR
  69563. var xhr = new XMLHttpRequest();
  69564. var fileData;
  69565. xhr.open("GET", url, true);
  69566. if (useArrayBuffer) {
  69567. xhr.responseType = "arraybuffer";
  69568. }
  69569. if (progressCallback) {
  69570. xhr.onprogress = progressCallback;
  69571. }
  69572. xhr.addEventListener("load", function () {
  69573. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69574. // Blob as response (XHR2)
  69575. //fileData = xhr.responseText;
  69576. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69577. if (!_this.hasReachedQuota && _this.db) {
  69578. // Open a transaction to the database
  69579. var transaction = _this.db.transaction([targetStore], "readwrite");
  69580. // the transaction could abort because of a QuotaExceededError error
  69581. transaction.onabort = function (event) {
  69582. try {
  69583. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69584. var error = event.srcElement['error'];
  69585. if (error && error.name === "QuotaExceededError") {
  69586. _this.hasReachedQuota = true;
  69587. }
  69588. }
  69589. catch (ex) { }
  69590. callback(fileData);
  69591. };
  69592. transaction.oncomplete = function (event) {
  69593. callback(fileData);
  69594. };
  69595. var newFile;
  69596. if (targetStore === "scenes") {
  69597. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69598. }
  69599. else {
  69600. newFile = { textureUrl: url, data: fileData };
  69601. }
  69602. try {
  69603. // Put the scene into the database
  69604. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69605. addRequest.onsuccess = function (event) {
  69606. };
  69607. addRequest.onerror = function (event) {
  69608. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69609. };
  69610. }
  69611. catch (ex) {
  69612. callback(fileData);
  69613. }
  69614. }
  69615. else {
  69616. callback(fileData);
  69617. }
  69618. }
  69619. else {
  69620. callback();
  69621. }
  69622. }, false);
  69623. xhr.addEventListener("error", function (event) {
  69624. BABYLON.Tools.Error("error on XHR request.");
  69625. callback();
  69626. }, false);
  69627. xhr.send();
  69628. }
  69629. else {
  69630. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69631. callback();
  69632. }
  69633. };
  69634. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69635. Database.IsUASupportingBlobStorage = true;
  69636. /** Gets a boolean indicating if Database storate is enabled */
  69637. Database.IDBStorageEnabled = true;
  69638. Database._ParseURL = function (url) {
  69639. var a = document.createElement('a');
  69640. a.href = url;
  69641. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69642. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69643. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69644. return absLocation;
  69645. };
  69646. Database._ReturnFullUrlLocation = function (url) {
  69647. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69648. return (Database._ParseURL(window.location.href) + url);
  69649. }
  69650. else {
  69651. return url;
  69652. }
  69653. };
  69654. return Database;
  69655. }());
  69656. BABYLON.Database = Database;
  69657. })(BABYLON || (BABYLON = {}));
  69658. //# sourceMappingURL=babylon.database.js.map
  69659. var BABYLON;
  69660. (function (BABYLON) {
  69661. var FresnelParameters = /** @class */ (function () {
  69662. function FresnelParameters() {
  69663. this._isEnabled = true;
  69664. this.leftColor = BABYLON.Color3.White();
  69665. this.rightColor = BABYLON.Color3.Black();
  69666. this.bias = 0;
  69667. this.power = 1;
  69668. }
  69669. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69670. get: function () {
  69671. return this._isEnabled;
  69672. },
  69673. set: function (value) {
  69674. if (this._isEnabled === value) {
  69675. return;
  69676. }
  69677. this._isEnabled = value;
  69678. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69679. },
  69680. enumerable: true,
  69681. configurable: true
  69682. });
  69683. FresnelParameters.prototype.clone = function () {
  69684. var newFresnelParameters = new FresnelParameters();
  69685. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69686. return newFresnelParameters;
  69687. };
  69688. FresnelParameters.prototype.serialize = function () {
  69689. var serializationObject = {};
  69690. serializationObject.isEnabled = this.isEnabled;
  69691. serializationObject.leftColor = this.leftColor.asArray();
  69692. serializationObject.rightColor = this.rightColor.asArray();
  69693. serializationObject.bias = this.bias;
  69694. serializationObject.power = this.power;
  69695. return serializationObject;
  69696. };
  69697. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69698. var fresnelParameters = new FresnelParameters();
  69699. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69700. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69701. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69702. fresnelParameters.bias = parsedFresnelParameters.bias;
  69703. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69704. return fresnelParameters;
  69705. };
  69706. return FresnelParameters;
  69707. }());
  69708. BABYLON.FresnelParameters = FresnelParameters;
  69709. })(BABYLON || (BABYLON = {}));
  69710. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69711. var BABYLON;
  69712. (function (BABYLON) {
  69713. var MultiMaterial = /** @class */ (function (_super) {
  69714. __extends(MultiMaterial, _super);
  69715. function MultiMaterial(name, scene) {
  69716. var _this = _super.call(this, name, scene, true) || this;
  69717. scene.multiMaterials.push(_this);
  69718. _this.subMaterials = new Array();
  69719. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69720. return _this;
  69721. }
  69722. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69723. get: function () {
  69724. return this._subMaterials;
  69725. },
  69726. set: function (value) {
  69727. this._subMaterials = value;
  69728. this._hookArray(value);
  69729. },
  69730. enumerable: true,
  69731. configurable: true
  69732. });
  69733. MultiMaterial.prototype._hookArray = function (array) {
  69734. var _this = this;
  69735. var oldPush = array.push;
  69736. array.push = function () {
  69737. var items = [];
  69738. for (var _i = 0; _i < arguments.length; _i++) {
  69739. items[_i] = arguments[_i];
  69740. }
  69741. var result = oldPush.apply(array, items);
  69742. _this._markAllSubMeshesAsTexturesDirty();
  69743. return result;
  69744. };
  69745. var oldSplice = array.splice;
  69746. array.splice = function (index, deleteCount) {
  69747. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69748. _this._markAllSubMeshesAsTexturesDirty();
  69749. return deleted;
  69750. };
  69751. };
  69752. // Properties
  69753. MultiMaterial.prototype.getSubMaterial = function (index) {
  69754. if (index < 0 || index >= this.subMaterials.length) {
  69755. return this.getScene().defaultMaterial;
  69756. }
  69757. return this.subMaterials[index];
  69758. };
  69759. MultiMaterial.prototype.getActiveTextures = function () {
  69760. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69761. if (subMaterial) {
  69762. return subMaterial.getActiveTextures();
  69763. }
  69764. else {
  69765. return [];
  69766. }
  69767. }));
  69768. var _a;
  69769. };
  69770. // Methods
  69771. MultiMaterial.prototype.getClassName = function () {
  69772. return "MultiMaterial";
  69773. };
  69774. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69775. for (var index = 0; index < this.subMaterials.length; index++) {
  69776. var subMaterial = this.subMaterials[index];
  69777. if (subMaterial) {
  69778. if (subMaterial.storeEffectOnSubMeshes) {
  69779. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69780. return false;
  69781. }
  69782. continue;
  69783. }
  69784. if (!subMaterial.isReady(mesh)) {
  69785. return false;
  69786. }
  69787. }
  69788. }
  69789. return true;
  69790. };
  69791. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69792. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69793. for (var index = 0; index < this.subMaterials.length; index++) {
  69794. var subMaterial = null;
  69795. var current = this.subMaterials[index];
  69796. if (cloneChildren && current) {
  69797. subMaterial = current.clone(name + "-" + current.name);
  69798. }
  69799. else {
  69800. subMaterial = this.subMaterials[index];
  69801. }
  69802. newMultiMaterial.subMaterials.push(subMaterial);
  69803. }
  69804. return newMultiMaterial;
  69805. };
  69806. MultiMaterial.prototype.serialize = function () {
  69807. var serializationObject = {};
  69808. serializationObject.name = this.name;
  69809. serializationObject.id = this.id;
  69810. if (BABYLON.Tags) {
  69811. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69812. }
  69813. serializationObject.materials = [];
  69814. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69815. var subMat = this.subMaterials[matIndex];
  69816. if (subMat) {
  69817. serializationObject.materials.push(subMat.id);
  69818. }
  69819. else {
  69820. serializationObject.materials.push(null);
  69821. }
  69822. }
  69823. return serializationObject;
  69824. };
  69825. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69826. var scene = this.getScene();
  69827. if (!scene) {
  69828. return;
  69829. }
  69830. var index = scene.multiMaterials.indexOf(this);
  69831. if (index >= 0) {
  69832. scene.multiMaterials.splice(index, 1);
  69833. }
  69834. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69835. };
  69836. return MultiMaterial;
  69837. }(BABYLON.Material));
  69838. BABYLON.MultiMaterial = MultiMaterial;
  69839. })(BABYLON || (BABYLON = {}));
  69840. //# sourceMappingURL=babylon.multiMaterial.js.map
  69841. var BABYLON;
  69842. (function (BABYLON) {
  69843. var FreeCameraTouchInput = /** @class */ (function () {
  69844. function FreeCameraTouchInput() {
  69845. this._offsetX = null;
  69846. this._offsetY = null;
  69847. this._pointerPressed = new Array();
  69848. this.touchAngularSensibility = 200000.0;
  69849. this.touchMoveSensibility = 250.0;
  69850. }
  69851. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69852. var _this = this;
  69853. var previousPosition = null;
  69854. if (this._pointerInput === undefined) {
  69855. this._onLostFocus = function (evt) {
  69856. _this._offsetX = null;
  69857. _this._offsetY = null;
  69858. };
  69859. this._pointerInput = function (p, s) {
  69860. var evt = p.event;
  69861. if (evt.pointerType === "mouse") {
  69862. return;
  69863. }
  69864. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69865. if (!noPreventDefault) {
  69866. evt.preventDefault();
  69867. }
  69868. _this._pointerPressed.push(evt.pointerId);
  69869. if (_this._pointerPressed.length !== 1) {
  69870. return;
  69871. }
  69872. previousPosition = {
  69873. x: evt.clientX,
  69874. y: evt.clientY
  69875. };
  69876. }
  69877. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69878. if (!noPreventDefault) {
  69879. evt.preventDefault();
  69880. }
  69881. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69882. if (index === -1) {
  69883. return;
  69884. }
  69885. _this._pointerPressed.splice(index, 1);
  69886. if (index != 0) {
  69887. return;
  69888. }
  69889. previousPosition = null;
  69890. _this._offsetX = null;
  69891. _this._offsetY = null;
  69892. }
  69893. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69894. if (!noPreventDefault) {
  69895. evt.preventDefault();
  69896. }
  69897. if (!previousPosition) {
  69898. return;
  69899. }
  69900. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69901. if (index != 0) {
  69902. return;
  69903. }
  69904. _this._offsetX = evt.clientX - previousPosition.x;
  69905. _this._offsetY = -(evt.clientY - previousPosition.y);
  69906. }
  69907. };
  69908. }
  69909. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69910. if (this._onLostFocus) {
  69911. element.addEventListener("blur", this._onLostFocus);
  69912. }
  69913. };
  69914. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69915. if (this._pointerInput && element) {
  69916. if (this._observer) {
  69917. this.camera.getScene().onPointerObservable.remove(this._observer);
  69918. this._observer = null;
  69919. }
  69920. if (this._onLostFocus) {
  69921. element.removeEventListener("blur", this._onLostFocus);
  69922. this._onLostFocus = null;
  69923. }
  69924. this._pointerPressed = [];
  69925. this._offsetX = null;
  69926. this._offsetY = null;
  69927. }
  69928. };
  69929. FreeCameraTouchInput.prototype.checkInputs = function () {
  69930. if (this._offsetX && this._offsetY) {
  69931. var camera = this.camera;
  69932. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69933. if (this._pointerPressed.length > 1) {
  69934. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69935. }
  69936. else {
  69937. var speed = camera._computeLocalCameraSpeed();
  69938. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69939. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69940. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69941. }
  69942. }
  69943. };
  69944. FreeCameraTouchInput.prototype.getClassName = function () {
  69945. return "FreeCameraTouchInput";
  69946. };
  69947. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69948. return "touch";
  69949. };
  69950. __decorate([
  69951. BABYLON.serialize()
  69952. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69953. __decorate([
  69954. BABYLON.serialize()
  69955. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69956. return FreeCameraTouchInput;
  69957. }());
  69958. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69959. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69960. })(BABYLON || (BABYLON = {}));
  69961. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69962. var BABYLON;
  69963. (function (BABYLON) {
  69964. // We're mainly based on the logic defined into the FreeCamera code
  69965. var TouchCamera = /** @class */ (function (_super) {
  69966. __extends(TouchCamera, _super);
  69967. //-- end properties for backward compatibility for inputs
  69968. function TouchCamera(name, position, scene) {
  69969. var _this = _super.call(this, name, position, scene) || this;
  69970. _this.inputs.addTouch();
  69971. _this._setupInputs();
  69972. return _this;
  69973. }
  69974. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69975. //-- Begin properties for backward compatibility for inputs
  69976. get: function () {
  69977. var touch = this.inputs.attached["touch"];
  69978. if (touch)
  69979. return touch.touchAngularSensibility;
  69980. return 0;
  69981. },
  69982. set: function (value) {
  69983. var touch = this.inputs.attached["touch"];
  69984. if (touch)
  69985. touch.touchAngularSensibility = value;
  69986. },
  69987. enumerable: true,
  69988. configurable: true
  69989. });
  69990. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69991. get: function () {
  69992. var touch = this.inputs.attached["touch"];
  69993. if (touch)
  69994. return touch.touchMoveSensibility;
  69995. return 0;
  69996. },
  69997. set: function (value) {
  69998. var touch = this.inputs.attached["touch"];
  69999. if (touch)
  70000. touch.touchMoveSensibility = value;
  70001. },
  70002. enumerable: true,
  70003. configurable: true
  70004. });
  70005. TouchCamera.prototype.getClassName = function () {
  70006. return "TouchCamera";
  70007. };
  70008. TouchCamera.prototype._setupInputs = function () {
  70009. var mouse = this.inputs.attached["mouse"];
  70010. if (mouse) {
  70011. mouse.touchEnabled = false;
  70012. }
  70013. };
  70014. return TouchCamera;
  70015. }(BABYLON.FreeCamera));
  70016. BABYLON.TouchCamera = TouchCamera;
  70017. })(BABYLON || (BABYLON = {}));
  70018. //# sourceMappingURL=babylon.touchCamera.js.map
  70019. var BABYLON;
  70020. (function (BABYLON) {
  70021. var ProceduralTexture = /** @class */ (function (_super) {
  70022. __extends(ProceduralTexture, _super);
  70023. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70024. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70025. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70026. if (isCube === void 0) { isCube = false; }
  70027. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70028. _this.isCube = isCube;
  70029. _this.isEnabled = true;
  70030. _this._currentRefreshId = -1;
  70031. _this._refreshRate = 1;
  70032. _this._vertexBuffers = {};
  70033. _this._uniforms = new Array();
  70034. _this._samplers = new Array();
  70035. _this._textures = {};
  70036. _this._floats = {};
  70037. _this._floatsArrays = {};
  70038. _this._colors3 = {};
  70039. _this._colors4 = {};
  70040. _this._vectors2 = {};
  70041. _this._vectors3 = {};
  70042. _this._matrices = {};
  70043. _this._fallbackTextureUsed = false;
  70044. scene.proceduralTextures.push(_this);
  70045. _this._engine = scene.getEngine();
  70046. _this.name = name;
  70047. _this.isRenderTarget = true;
  70048. _this._size = size;
  70049. _this._generateMipMaps = generateMipMaps;
  70050. _this.setFragment(fragment);
  70051. _this._fallbackTexture = fallbackTexture;
  70052. if (isCube) {
  70053. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70054. _this.setFloat("face", 0);
  70055. }
  70056. else {
  70057. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70058. }
  70059. // VBO
  70060. var vertices = [];
  70061. vertices.push(1, 1);
  70062. vertices.push(-1, 1);
  70063. vertices.push(-1, -1);
  70064. vertices.push(1, -1);
  70065. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70066. _this._createIndexBuffer();
  70067. return _this;
  70068. }
  70069. ProceduralTexture.prototype._createIndexBuffer = function () {
  70070. var engine = this._engine;
  70071. // Indices
  70072. var indices = [];
  70073. indices.push(0);
  70074. indices.push(1);
  70075. indices.push(2);
  70076. indices.push(0);
  70077. indices.push(2);
  70078. indices.push(3);
  70079. this._indexBuffer = engine.createIndexBuffer(indices);
  70080. };
  70081. ProceduralTexture.prototype._rebuild = function () {
  70082. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70083. if (vb) {
  70084. vb._rebuild();
  70085. }
  70086. this._createIndexBuffer();
  70087. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70088. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70089. }
  70090. };
  70091. ProceduralTexture.prototype.reset = function () {
  70092. if (this._effect === undefined) {
  70093. return;
  70094. }
  70095. var engine = this._engine;
  70096. engine._releaseEffect(this._effect);
  70097. };
  70098. ProceduralTexture.prototype.isReady = function () {
  70099. var _this = this;
  70100. var engine = this._engine;
  70101. var shaders;
  70102. if (!this._fragment) {
  70103. return false;
  70104. }
  70105. if (this._fallbackTextureUsed) {
  70106. return true;
  70107. }
  70108. if (this._fragment.fragmentElement !== undefined) {
  70109. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70110. }
  70111. else {
  70112. shaders = { vertex: "procedural", fragment: this._fragment };
  70113. }
  70114. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70115. _this.releaseInternalTexture();
  70116. if (_this._fallbackTexture) {
  70117. _this._texture = _this._fallbackTexture._texture;
  70118. if (_this._texture) {
  70119. _this._texture.incrementReferences();
  70120. }
  70121. }
  70122. _this._fallbackTextureUsed = true;
  70123. });
  70124. return this._effect.isReady();
  70125. };
  70126. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70127. this._currentRefreshId = -1;
  70128. };
  70129. ProceduralTexture.prototype.setFragment = function (fragment) {
  70130. this._fragment = fragment;
  70131. };
  70132. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70133. get: function () {
  70134. return this._refreshRate;
  70135. },
  70136. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70137. set: function (value) {
  70138. this._refreshRate = value;
  70139. this.resetRefreshCounter();
  70140. },
  70141. enumerable: true,
  70142. configurable: true
  70143. });
  70144. ProceduralTexture.prototype._shouldRender = function () {
  70145. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70146. return false;
  70147. }
  70148. if (this._fallbackTextureUsed) {
  70149. return false;
  70150. }
  70151. if (this._currentRefreshId === -1) { // At least render once
  70152. this._currentRefreshId = 1;
  70153. return true;
  70154. }
  70155. if (this.refreshRate === this._currentRefreshId) {
  70156. this._currentRefreshId = 1;
  70157. return true;
  70158. }
  70159. this._currentRefreshId++;
  70160. return false;
  70161. };
  70162. ProceduralTexture.prototype.getRenderSize = function () {
  70163. return this._size;
  70164. };
  70165. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70166. if (this._fallbackTextureUsed) {
  70167. return;
  70168. }
  70169. this.releaseInternalTexture();
  70170. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70171. };
  70172. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70173. if (this._uniforms.indexOf(uniformName) === -1) {
  70174. this._uniforms.push(uniformName);
  70175. }
  70176. };
  70177. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70178. if (this._samplers.indexOf(name) === -1) {
  70179. this._samplers.push(name);
  70180. }
  70181. this._textures[name] = texture;
  70182. return this;
  70183. };
  70184. ProceduralTexture.prototype.setFloat = function (name, value) {
  70185. this._checkUniform(name);
  70186. this._floats[name] = value;
  70187. return this;
  70188. };
  70189. ProceduralTexture.prototype.setFloats = function (name, value) {
  70190. this._checkUniform(name);
  70191. this._floatsArrays[name] = value;
  70192. return this;
  70193. };
  70194. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70195. this._checkUniform(name);
  70196. this._colors3[name] = value;
  70197. return this;
  70198. };
  70199. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70200. this._checkUniform(name);
  70201. this._colors4[name] = value;
  70202. return this;
  70203. };
  70204. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70205. this._checkUniform(name);
  70206. this._vectors2[name] = value;
  70207. return this;
  70208. };
  70209. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70210. this._checkUniform(name);
  70211. this._vectors3[name] = value;
  70212. return this;
  70213. };
  70214. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70215. this._checkUniform(name);
  70216. this._matrices[name] = value;
  70217. return this;
  70218. };
  70219. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70220. var scene = this.getScene();
  70221. if (!scene) {
  70222. return;
  70223. }
  70224. var engine = this._engine;
  70225. // Render
  70226. engine.enableEffect(this._effect);
  70227. engine.setState(false);
  70228. // Texture
  70229. for (var name in this._textures) {
  70230. this._effect.setTexture(name, this._textures[name]);
  70231. }
  70232. // Float
  70233. for (name in this._floats) {
  70234. this._effect.setFloat(name, this._floats[name]);
  70235. }
  70236. // Floats
  70237. for (name in this._floatsArrays) {
  70238. this._effect.setArray(name, this._floatsArrays[name]);
  70239. }
  70240. // Color3
  70241. for (name in this._colors3) {
  70242. this._effect.setColor3(name, this._colors3[name]);
  70243. }
  70244. // Color4
  70245. for (name in this._colors4) {
  70246. var color = this._colors4[name];
  70247. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70248. }
  70249. // Vector2
  70250. for (name in this._vectors2) {
  70251. this._effect.setVector2(name, this._vectors2[name]);
  70252. }
  70253. // Vector3
  70254. for (name in this._vectors3) {
  70255. this._effect.setVector3(name, this._vectors3[name]);
  70256. }
  70257. // Matrix
  70258. for (name in this._matrices) {
  70259. this._effect.setMatrix(name, this._matrices[name]);
  70260. }
  70261. if (!this._texture) {
  70262. return;
  70263. }
  70264. if (this.isCube) {
  70265. for (var face = 0; face < 6; face++) {
  70266. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70267. // VBOs
  70268. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70269. this._effect.setFloat("face", face);
  70270. // Clear
  70271. engine.clear(scene.clearColor, true, true, true);
  70272. // Draw order
  70273. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70274. // Mipmaps
  70275. if (face === 5) {
  70276. engine.generateMipMapsForCubemap(this._texture);
  70277. }
  70278. }
  70279. }
  70280. else {
  70281. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70282. // VBOs
  70283. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70284. // Clear
  70285. engine.clear(scene.clearColor, true, true, true);
  70286. // Draw order
  70287. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70288. }
  70289. // Unbind
  70290. engine.unBindFramebuffer(this._texture, this.isCube);
  70291. if (this.onGenerated) {
  70292. this.onGenerated();
  70293. }
  70294. };
  70295. ProceduralTexture.prototype.clone = function () {
  70296. var textureSize = this.getSize();
  70297. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70298. // Base texture
  70299. newTexture.hasAlpha = this.hasAlpha;
  70300. newTexture.level = this.level;
  70301. // RenderTarget Texture
  70302. newTexture.coordinatesMode = this.coordinatesMode;
  70303. return newTexture;
  70304. };
  70305. ProceduralTexture.prototype.dispose = function () {
  70306. var scene = this.getScene();
  70307. if (!scene) {
  70308. return;
  70309. }
  70310. var index = scene.proceduralTextures.indexOf(this);
  70311. if (index >= 0) {
  70312. scene.proceduralTextures.splice(index, 1);
  70313. }
  70314. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70315. if (vertexBuffer) {
  70316. vertexBuffer.dispose();
  70317. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70318. }
  70319. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70320. this._indexBuffer = null;
  70321. }
  70322. _super.prototype.dispose.call(this);
  70323. };
  70324. return ProceduralTexture;
  70325. }(BABYLON.Texture));
  70326. BABYLON.ProceduralTexture = ProceduralTexture;
  70327. })(BABYLON || (BABYLON = {}));
  70328. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70329. var BABYLON;
  70330. (function (BABYLON) {
  70331. var CustomProceduralTexture = /** @class */ (function (_super) {
  70332. __extends(CustomProceduralTexture, _super);
  70333. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70334. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70335. _this._animate = true;
  70336. _this._time = 0;
  70337. _this._texturePath = texturePath;
  70338. //Try to load json
  70339. _this.loadJson(texturePath);
  70340. _this.refreshRate = 1;
  70341. return _this;
  70342. }
  70343. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70344. var _this = this;
  70345. var noConfigFile = function () {
  70346. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70347. try {
  70348. _this.setFragment(_this._texturePath);
  70349. }
  70350. catch (ex) {
  70351. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70352. }
  70353. };
  70354. var configFileUrl = jsonUrl + "/config.json";
  70355. var xhr = new XMLHttpRequest();
  70356. xhr.open("GET", configFileUrl, true);
  70357. xhr.addEventListener("load", function () {
  70358. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70359. try {
  70360. _this._config = JSON.parse(xhr.response);
  70361. _this.updateShaderUniforms();
  70362. _this.updateTextures();
  70363. _this.setFragment(_this._texturePath + "/custom");
  70364. _this._animate = _this._config.animate;
  70365. _this.refreshRate = _this._config.refreshrate;
  70366. }
  70367. catch (ex) {
  70368. noConfigFile();
  70369. }
  70370. }
  70371. else {
  70372. noConfigFile();
  70373. }
  70374. }, false);
  70375. xhr.addEventListener("error", function () {
  70376. noConfigFile();
  70377. }, false);
  70378. try {
  70379. xhr.send();
  70380. }
  70381. catch (ex) {
  70382. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70383. }
  70384. };
  70385. CustomProceduralTexture.prototype.isReady = function () {
  70386. if (!_super.prototype.isReady.call(this)) {
  70387. return false;
  70388. }
  70389. for (var name in this._textures) {
  70390. var texture = this._textures[name];
  70391. if (!texture.isReady()) {
  70392. return false;
  70393. }
  70394. }
  70395. return true;
  70396. };
  70397. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70398. var scene = this.getScene();
  70399. if (this._animate && scene) {
  70400. this._time += scene.getAnimationRatio() * 0.03;
  70401. this.updateShaderUniforms();
  70402. }
  70403. _super.prototype.render.call(this, useCameraPostProcess);
  70404. };
  70405. CustomProceduralTexture.prototype.updateTextures = function () {
  70406. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70407. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70408. }
  70409. };
  70410. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70411. if (this._config) {
  70412. for (var j = 0; j < this._config.uniforms.length; j++) {
  70413. var uniform = this._config.uniforms[j];
  70414. switch (uniform.type) {
  70415. case "float":
  70416. this.setFloat(uniform.name, uniform.value);
  70417. break;
  70418. case "color3":
  70419. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70420. break;
  70421. case "color4":
  70422. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70423. break;
  70424. case "vector2":
  70425. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70426. break;
  70427. case "vector3":
  70428. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70429. break;
  70430. }
  70431. }
  70432. }
  70433. this.setFloat("time", this._time);
  70434. };
  70435. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70436. get: function () {
  70437. return this._animate;
  70438. },
  70439. set: function (value) {
  70440. this._animate = value;
  70441. },
  70442. enumerable: true,
  70443. configurable: true
  70444. });
  70445. return CustomProceduralTexture;
  70446. }(BABYLON.ProceduralTexture));
  70447. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70448. })(BABYLON || (BABYLON = {}));
  70449. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70450. var BABYLON;
  70451. (function (BABYLON) {
  70452. var FreeCameraGamepadInput = /** @class */ (function () {
  70453. function FreeCameraGamepadInput() {
  70454. this.gamepadAngularSensibility = 200;
  70455. this.gamepadMoveSensibility = 40;
  70456. // private members
  70457. this._cameraTransform = BABYLON.Matrix.Identity();
  70458. this._deltaTransform = BABYLON.Vector3.Zero();
  70459. this._vector3 = BABYLON.Vector3.Zero();
  70460. this._vector2 = BABYLON.Vector2.Zero();
  70461. }
  70462. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70463. var _this = this;
  70464. var manager = this.camera.getScene().gamepadManager;
  70465. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70466. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70467. // prioritize XBOX gamepads.
  70468. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70469. _this.gamepad = gamepad;
  70470. }
  70471. }
  70472. });
  70473. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70474. if (_this.gamepad === gamepad) {
  70475. _this.gamepad = null;
  70476. }
  70477. });
  70478. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70479. };
  70480. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70481. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70482. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70483. this.gamepad = null;
  70484. };
  70485. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70486. if (this.gamepad && this.gamepad.leftStick) {
  70487. var camera = this.camera;
  70488. var LSValues = this.gamepad.leftStick;
  70489. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70490. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70491. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70492. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70493. var RSValues = this.gamepad.rightStick;
  70494. if (RSValues) {
  70495. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70496. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70497. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70498. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70499. }
  70500. else {
  70501. RSValues = { x: 0, y: 0 };
  70502. }
  70503. if (!camera.rotationQuaternion) {
  70504. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70505. }
  70506. else {
  70507. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70508. }
  70509. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70510. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70511. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70512. camera.cameraDirection.addInPlace(this._deltaTransform);
  70513. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70514. camera.cameraRotation.addInPlace(this._vector2);
  70515. }
  70516. };
  70517. FreeCameraGamepadInput.prototype.getClassName = function () {
  70518. return "FreeCameraGamepadInput";
  70519. };
  70520. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70521. return "gamepad";
  70522. };
  70523. __decorate([
  70524. BABYLON.serialize()
  70525. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70526. __decorate([
  70527. BABYLON.serialize()
  70528. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70529. return FreeCameraGamepadInput;
  70530. }());
  70531. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70532. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70533. })(BABYLON || (BABYLON = {}));
  70534. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70535. var BABYLON;
  70536. (function (BABYLON) {
  70537. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70538. function ArcRotateCameraGamepadInput() {
  70539. this.gamepadRotationSensibility = 80;
  70540. this.gamepadMoveSensibility = 40;
  70541. }
  70542. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70543. var _this = this;
  70544. var manager = this.camera.getScene().gamepadManager;
  70545. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70546. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70547. // prioritize XBOX gamepads.
  70548. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70549. _this.gamepad = gamepad;
  70550. }
  70551. }
  70552. });
  70553. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70554. if (_this.gamepad === gamepad) {
  70555. _this.gamepad = null;
  70556. }
  70557. });
  70558. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70559. };
  70560. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70561. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70562. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70563. this.gamepad = null;
  70564. };
  70565. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70566. if (this.gamepad) {
  70567. var camera = this.camera;
  70568. var RSValues = this.gamepad.rightStick;
  70569. if (RSValues) {
  70570. if (RSValues.x != 0) {
  70571. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70572. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70573. camera.inertialAlphaOffset += normalizedRX;
  70574. }
  70575. }
  70576. if (RSValues.y != 0) {
  70577. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70578. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70579. camera.inertialBetaOffset += normalizedRY;
  70580. }
  70581. }
  70582. }
  70583. var LSValues = this.gamepad.leftStick;
  70584. if (LSValues && LSValues.y != 0) {
  70585. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70586. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70587. this.camera.inertialRadiusOffset -= normalizedLY;
  70588. }
  70589. }
  70590. }
  70591. };
  70592. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70593. return "ArcRotateCameraGamepadInput";
  70594. };
  70595. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70596. return "gamepad";
  70597. };
  70598. __decorate([
  70599. BABYLON.serialize()
  70600. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70601. __decorate([
  70602. BABYLON.serialize()
  70603. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70604. return ArcRotateCameraGamepadInput;
  70605. }());
  70606. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70607. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70608. })(BABYLON || (BABYLON = {}));
  70609. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70610. var BABYLON;
  70611. (function (BABYLON) {
  70612. var GamepadManager = /** @class */ (function () {
  70613. function GamepadManager(_scene) {
  70614. var _this = this;
  70615. this._scene = _scene;
  70616. this._babylonGamepads = [];
  70617. this._oneGamepadConnected = false;
  70618. this._isMonitoring = false;
  70619. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70620. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70621. this._gamepadEventSupported = false;
  70622. }
  70623. else {
  70624. this._gamepadEventSupported = 'GamepadEvent' in window;
  70625. this._gamepadSupport = (navigator.getGamepads ||
  70626. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70627. }
  70628. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70629. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70630. for (var i in _this._babylonGamepads) {
  70631. var gamepad = _this._babylonGamepads[i];
  70632. if (gamepad && gamepad._isConnected) {
  70633. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70634. }
  70635. }
  70636. });
  70637. this._onGamepadConnectedEvent = function (evt) {
  70638. var gamepad = evt.gamepad;
  70639. if (gamepad.index in _this._babylonGamepads) {
  70640. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70641. return;
  70642. }
  70643. }
  70644. var newGamepad;
  70645. if (_this._babylonGamepads[gamepad.index]) {
  70646. newGamepad = _this._babylonGamepads[gamepad.index];
  70647. newGamepad.browserGamepad = gamepad;
  70648. newGamepad._isConnected = true;
  70649. }
  70650. else {
  70651. newGamepad = _this._addNewGamepad(gamepad);
  70652. }
  70653. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70654. _this._startMonitoringGamepads();
  70655. };
  70656. this._onGamepadDisconnectedEvent = function (evt) {
  70657. var gamepad = evt.gamepad;
  70658. // Remove the gamepad from the list of gamepads to monitor.
  70659. for (var i in _this._babylonGamepads) {
  70660. if (_this._babylonGamepads[i].index === gamepad.index) {
  70661. var disconnectedGamepad = _this._babylonGamepads[i];
  70662. disconnectedGamepad._isConnected = false;
  70663. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70664. break;
  70665. }
  70666. }
  70667. };
  70668. if (this._gamepadSupport) {
  70669. //first add already-connected gamepads
  70670. this._updateGamepadObjects();
  70671. if (this._babylonGamepads.length) {
  70672. this._startMonitoringGamepads();
  70673. }
  70674. // Checking if the gamepad connected event is supported (like in Firefox)
  70675. if (this._gamepadEventSupported) {
  70676. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70677. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70678. }
  70679. else {
  70680. this._startMonitoringGamepads();
  70681. }
  70682. }
  70683. }
  70684. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70685. get: function () {
  70686. return this._babylonGamepads;
  70687. },
  70688. enumerable: true,
  70689. configurable: true
  70690. });
  70691. GamepadManager.prototype.getGamepadByType = function (type) {
  70692. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70693. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70694. var gamepad = _a[_i];
  70695. if (gamepad && gamepad.type === type) {
  70696. return gamepad;
  70697. }
  70698. }
  70699. return null;
  70700. };
  70701. GamepadManager.prototype.dispose = function () {
  70702. if (this._gamepadEventSupported) {
  70703. if (this._onGamepadConnectedEvent) {
  70704. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70705. }
  70706. if (this._onGamepadDisconnectedEvent) {
  70707. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70708. }
  70709. this._onGamepadConnectedEvent = null;
  70710. this._onGamepadDisconnectedEvent = null;
  70711. }
  70712. this._babylonGamepads.forEach(function (gamepad) {
  70713. gamepad.dispose();
  70714. });
  70715. this.onGamepadConnectedObservable.clear();
  70716. this.onGamepadDisconnectedObservable.clear();
  70717. this._oneGamepadConnected = false;
  70718. this._stopMonitoringGamepads();
  70719. this._babylonGamepads = [];
  70720. };
  70721. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70722. if (!this._oneGamepadConnected) {
  70723. this._oneGamepadConnected = true;
  70724. }
  70725. var newGamepad;
  70726. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70727. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70728. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70729. }
  70730. // if pose is supported, use the (WebVR) pose enabled controller
  70731. else if (gamepad.pose) {
  70732. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70733. }
  70734. else {
  70735. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70736. }
  70737. this._babylonGamepads[newGamepad.index] = newGamepad;
  70738. return newGamepad;
  70739. };
  70740. GamepadManager.prototype._startMonitoringGamepads = function () {
  70741. if (!this._isMonitoring) {
  70742. this._isMonitoring = true;
  70743. //back-comp
  70744. if (!this._scene) {
  70745. this._checkGamepadsStatus();
  70746. }
  70747. }
  70748. };
  70749. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70750. this._isMonitoring = false;
  70751. };
  70752. GamepadManager.prototype._checkGamepadsStatus = function () {
  70753. var _this = this;
  70754. // Hack to be compatible Chrome
  70755. this._updateGamepadObjects();
  70756. for (var i in this._babylonGamepads) {
  70757. var gamepad = this._babylonGamepads[i];
  70758. if (!gamepad || !gamepad.isConnected) {
  70759. continue;
  70760. }
  70761. gamepad.update();
  70762. }
  70763. if (this._isMonitoring && !this._scene) {
  70764. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70765. }
  70766. };
  70767. // This function is called only on Chrome, which does not properly support
  70768. // connection/disconnection events and forces you to recopy again the gamepad object
  70769. GamepadManager.prototype._updateGamepadObjects = function () {
  70770. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70771. for (var i = 0; i < gamepads.length; i++) {
  70772. var gamepad = gamepads[i];
  70773. if (gamepad) {
  70774. if (!this._babylonGamepads[gamepad.index]) {
  70775. var newGamepad = this._addNewGamepad(gamepad);
  70776. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70777. }
  70778. else {
  70779. // Forced to copy again this object for Chrome for unknown reason
  70780. this._babylonGamepads[i].browserGamepad = gamepad;
  70781. if (!this._babylonGamepads[i].isConnected) {
  70782. this._babylonGamepads[i]._isConnected = true;
  70783. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70784. }
  70785. }
  70786. }
  70787. }
  70788. };
  70789. return GamepadManager;
  70790. }());
  70791. BABYLON.GamepadManager = GamepadManager;
  70792. })(BABYLON || (BABYLON = {}));
  70793. //# sourceMappingURL=babylon.gamepadManager.js.map
  70794. var BABYLON;
  70795. (function (BABYLON) {
  70796. var StickValues = /** @class */ (function () {
  70797. function StickValues(x, y) {
  70798. this.x = x;
  70799. this.y = y;
  70800. }
  70801. return StickValues;
  70802. }());
  70803. BABYLON.StickValues = StickValues;
  70804. var Gamepad = /** @class */ (function () {
  70805. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70806. if (leftStickX === void 0) { leftStickX = 0; }
  70807. if (leftStickY === void 0) { leftStickY = 1; }
  70808. if (rightStickX === void 0) { rightStickX = 2; }
  70809. if (rightStickY === void 0) { rightStickY = 3; }
  70810. this.id = id;
  70811. this.index = index;
  70812. this.browserGamepad = browserGamepad;
  70813. this._isConnected = true;
  70814. this._invertLeftStickY = false;
  70815. this.type = Gamepad.GAMEPAD;
  70816. this._leftStickAxisX = leftStickX;
  70817. this._leftStickAxisY = leftStickY;
  70818. this._rightStickAxisX = rightStickX;
  70819. this._rightStickAxisY = rightStickY;
  70820. if (this.browserGamepad.axes.length >= 2) {
  70821. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70822. }
  70823. if (this.browserGamepad.axes.length >= 4) {
  70824. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70825. }
  70826. }
  70827. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70828. get: function () {
  70829. return this._isConnected;
  70830. },
  70831. enumerable: true,
  70832. configurable: true
  70833. });
  70834. Gamepad.prototype.onleftstickchanged = function (callback) {
  70835. this._onleftstickchanged = callback;
  70836. };
  70837. Gamepad.prototype.onrightstickchanged = function (callback) {
  70838. this._onrightstickchanged = callback;
  70839. };
  70840. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70841. get: function () {
  70842. return this._leftStick;
  70843. },
  70844. set: function (newValues) {
  70845. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70846. this._onleftstickchanged(newValues);
  70847. }
  70848. this._leftStick = newValues;
  70849. },
  70850. enumerable: true,
  70851. configurable: true
  70852. });
  70853. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70854. get: function () {
  70855. return this._rightStick;
  70856. },
  70857. set: function (newValues) {
  70858. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70859. this._onrightstickchanged(newValues);
  70860. }
  70861. this._rightStick = newValues;
  70862. },
  70863. enumerable: true,
  70864. configurable: true
  70865. });
  70866. Gamepad.prototype.update = function () {
  70867. if (this._leftStick) {
  70868. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70869. if (this._invertLeftStickY) {
  70870. this.leftStick.y *= -1;
  70871. }
  70872. }
  70873. if (this._rightStick) {
  70874. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70875. }
  70876. };
  70877. Gamepad.prototype.dispose = function () {
  70878. };
  70879. Gamepad.GAMEPAD = 0;
  70880. Gamepad.GENERIC = 1;
  70881. Gamepad.XBOX = 2;
  70882. Gamepad.POSE_ENABLED = 3;
  70883. return Gamepad;
  70884. }());
  70885. BABYLON.Gamepad = Gamepad;
  70886. var GenericPad = /** @class */ (function (_super) {
  70887. __extends(GenericPad, _super);
  70888. function GenericPad(id, index, browserGamepad) {
  70889. var _this = _super.call(this, id, index, browserGamepad) || this;
  70890. _this.onButtonDownObservable = new BABYLON.Observable();
  70891. _this.onButtonUpObservable = new BABYLON.Observable();
  70892. _this.type = Gamepad.GENERIC;
  70893. _this._buttons = new Array(browserGamepad.buttons.length);
  70894. return _this;
  70895. }
  70896. GenericPad.prototype.onbuttondown = function (callback) {
  70897. this._onbuttondown = callback;
  70898. };
  70899. GenericPad.prototype.onbuttonup = function (callback) {
  70900. this._onbuttonup = callback;
  70901. };
  70902. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70903. if (newValue !== currentValue) {
  70904. if (newValue === 1) {
  70905. if (this._onbuttondown) {
  70906. this._onbuttondown(buttonIndex);
  70907. }
  70908. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70909. }
  70910. if (newValue === 0) {
  70911. if (this._onbuttonup) {
  70912. this._onbuttonup(buttonIndex);
  70913. }
  70914. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70915. }
  70916. }
  70917. return newValue;
  70918. };
  70919. GenericPad.prototype.update = function () {
  70920. _super.prototype.update.call(this);
  70921. for (var index = 0; index < this._buttons.length; index++) {
  70922. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70923. }
  70924. };
  70925. GenericPad.prototype.dispose = function () {
  70926. _super.prototype.dispose.call(this);
  70927. this.onButtonDownObservable.clear();
  70928. this.onButtonUpObservable.clear();
  70929. };
  70930. return GenericPad;
  70931. }(Gamepad));
  70932. BABYLON.GenericPad = GenericPad;
  70933. })(BABYLON || (BABYLON = {}));
  70934. //# sourceMappingURL=babylon.gamepad.js.map
  70935. var BABYLON;
  70936. (function (BABYLON) {
  70937. /**
  70938. * Defines supported buttons for XBox360 compatible gamepads
  70939. */
  70940. var Xbox360Button;
  70941. (function (Xbox360Button) {
  70942. /** A */
  70943. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70944. /** B */
  70945. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70946. /** X */
  70947. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70948. /** Y */
  70949. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70950. /** Start */
  70951. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70952. /** Back */
  70953. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70954. /** Left button */
  70955. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70956. /** Right button */
  70957. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70958. /** Left stick */
  70959. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70960. /** Right stick */
  70961. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70962. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70963. /** Defines values for XBox360 DPad */
  70964. var Xbox360Dpad;
  70965. (function (Xbox360Dpad) {
  70966. /** Up */
  70967. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70968. /** Down */
  70969. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70970. /** Left */
  70971. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70972. /** Right */
  70973. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70974. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70975. /**
  70976. * Defines a XBox360 gamepad
  70977. */
  70978. var Xbox360Pad = /** @class */ (function (_super) {
  70979. __extends(Xbox360Pad, _super);
  70980. /**
  70981. * Creates a new XBox360 gamepad object
  70982. * @param id defines the id of this gamepad
  70983. * @param index defines its index
  70984. * @param gamepad defines the internal HTML gamepad object
  70985. * @param xboxOne defines if it is a XBox One gamepad
  70986. */
  70987. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70988. if (xboxOne === void 0) { xboxOne = false; }
  70989. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70990. _this._leftTrigger = 0;
  70991. _this._rightTrigger = 0;
  70992. /** Observable raised when a button is pressed */
  70993. _this.onButtonDownObservable = new BABYLON.Observable();
  70994. /** Observable raised when a button is released */
  70995. _this.onButtonUpObservable = new BABYLON.Observable();
  70996. /** Observable raised when a pad is pressed */
  70997. _this.onPadDownObservable = new BABYLON.Observable();
  70998. /** Observable raised when a pad is released */
  70999. _this.onPadUpObservable = new BABYLON.Observable();
  71000. _this._buttonA = 0;
  71001. _this._buttonB = 0;
  71002. _this._buttonX = 0;
  71003. _this._buttonY = 0;
  71004. _this._buttonBack = 0;
  71005. _this._buttonStart = 0;
  71006. _this._buttonLB = 0;
  71007. _this._buttonRB = 0;
  71008. _this._buttonLeftStick = 0;
  71009. _this._buttonRightStick = 0;
  71010. _this._dPadUp = 0;
  71011. _this._dPadDown = 0;
  71012. _this._dPadLeft = 0;
  71013. _this._dPadRight = 0;
  71014. _this._isXboxOnePad = false;
  71015. _this.type = BABYLON.Gamepad.XBOX;
  71016. _this._isXboxOnePad = xboxOne;
  71017. return _this;
  71018. }
  71019. /**
  71020. * Defines the callback to call when left trigger is pressed
  71021. * @param callback defines the callback to use
  71022. */
  71023. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71024. this._onlefttriggerchanged = callback;
  71025. };
  71026. /**
  71027. * Defines the callback to call when right trigger is pressed
  71028. * @param callback defines the callback to use
  71029. */
  71030. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71031. this._onrighttriggerchanged = callback;
  71032. };
  71033. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71034. /**
  71035. * Gets or sets left trigger value
  71036. */
  71037. get: function () {
  71038. return this._leftTrigger;
  71039. },
  71040. set: function (newValue) {
  71041. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71042. this._onlefttriggerchanged(newValue);
  71043. }
  71044. this._leftTrigger = newValue;
  71045. },
  71046. enumerable: true,
  71047. configurable: true
  71048. });
  71049. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71050. /**
  71051. * Gets or sets right trigger value
  71052. */
  71053. get: function () {
  71054. return this._rightTrigger;
  71055. },
  71056. set: function (newValue) {
  71057. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71058. this._onrighttriggerchanged(newValue);
  71059. }
  71060. this._rightTrigger = newValue;
  71061. },
  71062. enumerable: true,
  71063. configurable: true
  71064. });
  71065. /**
  71066. * Defines the callback to call when a button is pressed
  71067. * @param callback defines the callback to use
  71068. */
  71069. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71070. this._onbuttondown = callback;
  71071. };
  71072. /**
  71073. * Defines the callback to call when a button is released
  71074. * @param callback defines the callback to use
  71075. */
  71076. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71077. this._onbuttonup = callback;
  71078. };
  71079. /**
  71080. * Defines the callback to call when a pad is pressed
  71081. * @param callback defines the callback to use
  71082. */
  71083. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71084. this._ondpaddown = callback;
  71085. };
  71086. /**
  71087. * Defines the callback to call when a pad is released
  71088. * @param callback defines the callback to use
  71089. */
  71090. Xbox360Pad.prototype.ondpadup = function (callback) {
  71091. this._ondpadup = callback;
  71092. };
  71093. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71094. if (newValue !== currentValue) {
  71095. if (newValue === 1) {
  71096. if (this._onbuttondown) {
  71097. this._onbuttondown(buttonType);
  71098. }
  71099. this.onButtonDownObservable.notifyObservers(buttonType);
  71100. }
  71101. if (newValue === 0) {
  71102. if (this._onbuttonup) {
  71103. this._onbuttonup(buttonType);
  71104. }
  71105. this.onButtonUpObservable.notifyObservers(buttonType);
  71106. }
  71107. }
  71108. return newValue;
  71109. };
  71110. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71111. if (newValue !== currentValue) {
  71112. if (newValue === 1) {
  71113. if (this._ondpaddown) {
  71114. this._ondpaddown(buttonType);
  71115. }
  71116. this.onPadDownObservable.notifyObservers(buttonType);
  71117. }
  71118. if (newValue === 0) {
  71119. if (this._ondpadup) {
  71120. this._ondpadup(buttonType);
  71121. }
  71122. this.onPadUpObservable.notifyObservers(buttonType);
  71123. }
  71124. }
  71125. return newValue;
  71126. };
  71127. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71128. /** Gets or sets value of A button */
  71129. get: function () {
  71130. return this._buttonA;
  71131. },
  71132. set: function (value) {
  71133. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71134. },
  71135. enumerable: true,
  71136. configurable: true
  71137. });
  71138. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71139. /** Gets or sets value of B button */
  71140. get: function () {
  71141. return this._buttonB;
  71142. },
  71143. set: function (value) {
  71144. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71145. },
  71146. enumerable: true,
  71147. configurable: true
  71148. });
  71149. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71150. /** Gets or sets value of X button */
  71151. get: function () {
  71152. return this._buttonX;
  71153. },
  71154. set: function (value) {
  71155. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71156. },
  71157. enumerable: true,
  71158. configurable: true
  71159. });
  71160. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71161. /** Gets or sets value of Y button */
  71162. get: function () {
  71163. return this._buttonY;
  71164. },
  71165. set: function (value) {
  71166. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71167. },
  71168. enumerable: true,
  71169. configurable: true
  71170. });
  71171. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71172. /** Gets or sets value of Start button */
  71173. get: function () {
  71174. return this._buttonStart;
  71175. },
  71176. set: function (value) {
  71177. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71178. },
  71179. enumerable: true,
  71180. configurable: true
  71181. });
  71182. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71183. /** Gets or sets value of Back button */
  71184. get: function () {
  71185. return this._buttonBack;
  71186. },
  71187. set: function (value) {
  71188. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71189. },
  71190. enumerable: true,
  71191. configurable: true
  71192. });
  71193. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71194. /** Gets or sets value of Left button */
  71195. get: function () {
  71196. return this._buttonLB;
  71197. },
  71198. set: function (value) {
  71199. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71200. },
  71201. enumerable: true,
  71202. configurable: true
  71203. });
  71204. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71205. /** Gets or sets value of Right button */
  71206. get: function () {
  71207. return this._buttonRB;
  71208. },
  71209. set: function (value) {
  71210. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71211. },
  71212. enumerable: true,
  71213. configurable: true
  71214. });
  71215. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71216. /** Gets or sets value of left stick */
  71217. get: function () {
  71218. return this._buttonLeftStick;
  71219. },
  71220. set: function (value) {
  71221. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71222. },
  71223. enumerable: true,
  71224. configurable: true
  71225. });
  71226. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71227. /** Gets or sets value of right stick */
  71228. get: function () {
  71229. return this._buttonRightStick;
  71230. },
  71231. set: function (value) {
  71232. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71233. },
  71234. enumerable: true,
  71235. configurable: true
  71236. });
  71237. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71238. /** Gets or sets value of DPad up */
  71239. get: function () {
  71240. return this._dPadUp;
  71241. },
  71242. set: function (value) {
  71243. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71244. },
  71245. enumerable: true,
  71246. configurable: true
  71247. });
  71248. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71249. /** Gets or sets value of DPad down */
  71250. get: function () {
  71251. return this._dPadDown;
  71252. },
  71253. set: function (value) {
  71254. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71255. },
  71256. enumerable: true,
  71257. configurable: true
  71258. });
  71259. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71260. /** Gets or sets value of DPad left */
  71261. get: function () {
  71262. return this._dPadLeft;
  71263. },
  71264. set: function (value) {
  71265. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71266. },
  71267. enumerable: true,
  71268. configurable: true
  71269. });
  71270. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71271. /** Gets or sets value of DPad right */
  71272. get: function () {
  71273. return this._dPadRight;
  71274. },
  71275. set: function (value) {
  71276. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71277. },
  71278. enumerable: true,
  71279. configurable: true
  71280. });
  71281. /**
  71282. * Force the gamepad to synchronize with device values
  71283. */
  71284. Xbox360Pad.prototype.update = function () {
  71285. _super.prototype.update.call(this);
  71286. if (this._isXboxOnePad) {
  71287. this.buttonA = this.browserGamepad.buttons[0].value;
  71288. this.buttonB = this.browserGamepad.buttons[1].value;
  71289. this.buttonX = this.browserGamepad.buttons[2].value;
  71290. this.buttonY = this.browserGamepad.buttons[3].value;
  71291. this.buttonLB = this.browserGamepad.buttons[4].value;
  71292. this.buttonRB = this.browserGamepad.buttons[5].value;
  71293. this.leftTrigger = this.browserGamepad.axes[2];
  71294. this.rightTrigger = this.browserGamepad.axes[5];
  71295. this.buttonBack = this.browserGamepad.buttons[9].value;
  71296. this.buttonStart = this.browserGamepad.buttons[8].value;
  71297. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71298. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71299. this.dPadUp = this.browserGamepad.buttons[11].value;
  71300. this.dPadDown = this.browserGamepad.buttons[12].value;
  71301. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71302. this.dPadRight = this.browserGamepad.buttons[14].value;
  71303. }
  71304. else {
  71305. this.buttonA = this.browserGamepad.buttons[0].value;
  71306. this.buttonB = this.browserGamepad.buttons[1].value;
  71307. this.buttonX = this.browserGamepad.buttons[2].value;
  71308. this.buttonY = this.browserGamepad.buttons[3].value;
  71309. this.buttonLB = this.browserGamepad.buttons[4].value;
  71310. this.buttonRB = this.browserGamepad.buttons[5].value;
  71311. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71312. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71313. this.buttonBack = this.browserGamepad.buttons[8].value;
  71314. this.buttonStart = this.browserGamepad.buttons[9].value;
  71315. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71316. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71317. this.dPadUp = this.browserGamepad.buttons[12].value;
  71318. this.dPadDown = this.browserGamepad.buttons[13].value;
  71319. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71320. this.dPadRight = this.browserGamepad.buttons[15].value;
  71321. }
  71322. };
  71323. Xbox360Pad.prototype.dispose = function () {
  71324. _super.prototype.dispose.call(this);
  71325. this.onButtonDownObservable.clear();
  71326. this.onButtonUpObservable.clear();
  71327. this.onPadDownObservable.clear();
  71328. this.onPadUpObservable.clear();
  71329. };
  71330. return Xbox360Pad;
  71331. }(BABYLON.Gamepad));
  71332. BABYLON.Xbox360Pad = Xbox360Pad;
  71333. })(BABYLON || (BABYLON = {}));
  71334. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71335. var BABYLON;
  71336. (function (BABYLON) {
  71337. /**
  71338. * Defines the types of pose enabled controllers that are supported
  71339. */
  71340. var PoseEnabledControllerType;
  71341. (function (PoseEnabledControllerType) {
  71342. /**
  71343. * HTC Vive
  71344. */
  71345. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71346. /**
  71347. * Oculus Rift
  71348. */
  71349. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71350. /**
  71351. * Windows mixed reality
  71352. */
  71353. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71354. /**
  71355. * Samsung gear VR
  71356. */
  71357. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71358. /**
  71359. * Google Daydream
  71360. */
  71361. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71362. /**
  71363. * Generic
  71364. */
  71365. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71366. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71367. /**
  71368. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71369. */
  71370. var PoseEnabledControllerHelper = /** @class */ (function () {
  71371. function PoseEnabledControllerHelper() {
  71372. }
  71373. /**
  71374. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71375. * @param vrGamepad the gamepad to initialized
  71376. * @returns a vr controller of the type the gamepad identified as
  71377. */
  71378. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71379. // Oculus Touch
  71380. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71381. return new BABYLON.OculusTouchController(vrGamepad);
  71382. }
  71383. // Windows Mixed Reality controllers
  71384. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71385. return new BABYLON.WindowsMotionController(vrGamepad);
  71386. }
  71387. // HTC Vive
  71388. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71389. return new BABYLON.ViveController(vrGamepad);
  71390. }
  71391. // Samsung/Oculus Gear VR or Oculus Go
  71392. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71393. return new BABYLON.GearVRController(vrGamepad);
  71394. }
  71395. // Google Daydream
  71396. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71397. return new BABYLON.DaydreamController(vrGamepad);
  71398. }
  71399. // Generic
  71400. else {
  71401. return new BABYLON.GenericController(vrGamepad);
  71402. }
  71403. };
  71404. return PoseEnabledControllerHelper;
  71405. }());
  71406. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71407. /**
  71408. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71409. */
  71410. var PoseEnabledController = /** @class */ (function (_super) {
  71411. __extends(PoseEnabledController, _super);
  71412. /**
  71413. * Creates a new PoseEnabledController from a gamepad
  71414. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71415. */
  71416. function PoseEnabledController(browserGamepad) {
  71417. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71418. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71419. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71420. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71421. /**
  71422. * The device position in babylon space
  71423. */
  71424. _this.devicePosition = BABYLON.Vector3.Zero();
  71425. /**
  71426. * The device rotation in babylon space
  71427. */
  71428. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71429. /**
  71430. * The scale factor of the device in babylon space
  71431. */
  71432. _this.deviceScaleFactor = 1;
  71433. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71434. /**
  71435. * Internal, matrix used to convert room space to babylon space
  71436. */
  71437. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71438. /**
  71439. * Node to be used when casting a ray from the controller
  71440. */
  71441. _this._pointingPoseNode = null;
  71442. _this._workingMatrix = BABYLON.Matrix.Identity();
  71443. /**
  71444. * @hidden
  71445. */
  71446. _this._meshAttachedObservable = new BABYLON.Observable();
  71447. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71448. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71449. _this.position = BABYLON.Vector3.Zero();
  71450. _this.rotationQuaternion = new BABYLON.Quaternion();
  71451. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71452. _this._calculatedRotation = new BABYLON.Quaternion();
  71453. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71454. return _this;
  71455. }
  71456. /**
  71457. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71458. */
  71459. PoseEnabledController.prototype.update = function () {
  71460. _super.prototype.update.call(this);
  71461. var pose = this.browserGamepad.pose;
  71462. this.updateFromDevice(pose);
  71463. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71464. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71465. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71466. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71467. if (this._mesh) {
  71468. this._mesh.position.copyFrom(this.devicePosition);
  71469. if (this._mesh.rotationQuaternion) {
  71470. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71471. }
  71472. }
  71473. };
  71474. /**
  71475. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71476. * @param poseData raw pose fromthe device
  71477. */
  71478. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71479. if (poseData) {
  71480. this.rawPose = poseData;
  71481. if (poseData.position) {
  71482. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71483. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71484. this._deviceRoomPosition.z *= -1;
  71485. }
  71486. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71487. this._calculatedPosition.addInPlace(this.position);
  71488. }
  71489. var pose = this.rawPose;
  71490. if (poseData.orientation && pose.orientation) {
  71491. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71492. if (this._mesh) {
  71493. if (this._mesh.getScene().useRightHandedSystem) {
  71494. this._deviceRoomRotationQuaternion.z *= -1;
  71495. this._deviceRoomRotationQuaternion.w *= -1;
  71496. }
  71497. else {
  71498. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71499. }
  71500. }
  71501. // if the camera is set, rotate to the camera's rotation
  71502. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71503. }
  71504. }
  71505. };
  71506. /**
  71507. * Attaches a mesh to the controller
  71508. * @param mesh the mesh to be attached
  71509. */
  71510. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71511. if (this._mesh) {
  71512. this._mesh.parent = null;
  71513. }
  71514. this._mesh = mesh;
  71515. if (this._poseControlledCamera) {
  71516. this._mesh.parent = this._poseControlledCamera;
  71517. }
  71518. if (!this._mesh.rotationQuaternion) {
  71519. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71520. }
  71521. this._meshAttachedObservable.notifyObservers(mesh);
  71522. };
  71523. /**
  71524. * Attaches the controllers mesh to a camera
  71525. * @param camera the camera the mesh should be attached to
  71526. */
  71527. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71528. this._poseControlledCamera = camera;
  71529. if (this._mesh) {
  71530. this._mesh.parent = this._poseControlledCamera;
  71531. }
  71532. };
  71533. /**
  71534. * Disposes of the controller
  71535. */
  71536. PoseEnabledController.prototype.dispose = function () {
  71537. if (this._mesh) {
  71538. this._mesh.dispose();
  71539. }
  71540. this._mesh = null;
  71541. _super.prototype.dispose.call(this);
  71542. };
  71543. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71544. /**
  71545. * The mesh that is attached to the controller
  71546. */
  71547. get: function () {
  71548. return this._mesh;
  71549. },
  71550. enumerable: true,
  71551. configurable: true
  71552. });
  71553. /**
  71554. * Gets the ray of the controller in the direction the controller is pointing
  71555. * @param length the length the resulting ray should be
  71556. * @returns a ray in the direction the controller is pointing
  71557. */
  71558. PoseEnabledController.prototype.getForwardRay = function (length) {
  71559. if (length === void 0) { length = 100; }
  71560. if (!this.mesh) {
  71561. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71562. }
  71563. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71564. var origin = m.getTranslation();
  71565. var forward = new BABYLON.Vector3(0, 0, -1);
  71566. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71567. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71568. return new BABYLON.Ray(origin, direction, length);
  71569. };
  71570. /**
  71571. * Name of the child mesh that can be used to cast a ray from the controller
  71572. */
  71573. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71574. return PoseEnabledController;
  71575. }(BABYLON.Gamepad));
  71576. BABYLON.PoseEnabledController = PoseEnabledController;
  71577. })(BABYLON || (BABYLON = {}));
  71578. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71579. var BABYLON;
  71580. (function (BABYLON) {
  71581. /**
  71582. * Defines the WebVRController object that represents controllers tracked in 3D space
  71583. */
  71584. var WebVRController = /** @class */ (function (_super) {
  71585. __extends(WebVRController, _super);
  71586. /**
  71587. * Creates a new WebVRController from a gamepad
  71588. * @param vrGamepad the gamepad that the WebVRController should be created from
  71589. */
  71590. function WebVRController(vrGamepad) {
  71591. var _this = _super.call(this, vrGamepad) || this;
  71592. // Observables
  71593. /**
  71594. * Fired when the trigger state has changed
  71595. */
  71596. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71597. /**
  71598. * Fired when the main button state has changed
  71599. */
  71600. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71601. /**
  71602. * Fired when the secondary button state has changed
  71603. */
  71604. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71605. /**
  71606. * Fired when the pad state has changed
  71607. */
  71608. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71609. /**
  71610. * Fired when controllers stick values have changed
  71611. */
  71612. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71613. /**
  71614. * X and Y axis corrisponding to the controllers joystick
  71615. */
  71616. _this.pad = { x: 0, y: 0 };
  71617. // avoid GC, store state in a tmp object
  71618. _this._changes = {
  71619. pressChanged: false,
  71620. touchChanged: false,
  71621. valueChanged: false,
  71622. changed: false
  71623. };
  71624. _this._buttons = new Array(vrGamepad.buttons.length);
  71625. _this.hand = vrGamepad.hand;
  71626. return _this;
  71627. }
  71628. /**
  71629. * Fired when a controller button's state has changed
  71630. * @param callback the callback containing the button that was modified
  71631. */
  71632. WebVRController.prototype.onButtonStateChange = function (callback) {
  71633. this._onButtonStateChange = callback;
  71634. };
  71635. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71636. /**
  71637. * The default controller model for the controller
  71638. */
  71639. get: function () {
  71640. return this._defaultModel;
  71641. },
  71642. enumerable: true,
  71643. configurable: true
  71644. });
  71645. /**
  71646. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71647. */
  71648. WebVRController.prototype.update = function () {
  71649. _super.prototype.update.call(this);
  71650. for (var index = 0; index < this._buttons.length; index++) {
  71651. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71652. }
  71653. ;
  71654. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71655. this.pad.x = this.leftStick.x;
  71656. this.pad.y = this.leftStick.y;
  71657. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71658. }
  71659. };
  71660. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71661. if (!newState) {
  71662. newState = {
  71663. pressed: false,
  71664. touched: false,
  71665. value: 0
  71666. };
  71667. }
  71668. if (!currentState) {
  71669. this._buttons[buttonIndex] = {
  71670. pressed: newState.pressed,
  71671. touched: newState.touched,
  71672. value: newState.value
  71673. };
  71674. return;
  71675. }
  71676. this._checkChanges(newState, currentState);
  71677. if (this._changes.changed) {
  71678. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71679. this._handleButtonChange(buttonIndex, newState, this._changes);
  71680. }
  71681. this._buttons[buttonIndex].pressed = newState.pressed;
  71682. this._buttons[buttonIndex].touched = newState.touched;
  71683. // oculus triggers are never 0, thou not touched.
  71684. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71685. };
  71686. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71687. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71688. this._changes.touchChanged = newState.touched !== currentState.touched;
  71689. this._changes.valueChanged = newState.value !== currentState.value;
  71690. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71691. return this._changes;
  71692. };
  71693. /**
  71694. * Disposes of th webVRCOntroller
  71695. */
  71696. WebVRController.prototype.dispose = function () {
  71697. _super.prototype.dispose.call(this);
  71698. this.onTriggerStateChangedObservable.clear();
  71699. this.onMainButtonStateChangedObservable.clear();
  71700. this.onSecondaryButtonStateChangedObservable.clear();
  71701. this.onPadStateChangedObservable.clear();
  71702. this.onPadValuesChangedObservable.clear();
  71703. };
  71704. return WebVRController;
  71705. }(BABYLON.PoseEnabledController));
  71706. BABYLON.WebVRController = WebVRController;
  71707. })(BABYLON || (BABYLON = {}));
  71708. //# sourceMappingURL=babylon.webVRController.js.map
  71709. var BABYLON;
  71710. (function (BABYLON) {
  71711. /**
  71712. * Oculus Touch Controller
  71713. */
  71714. var OculusTouchController = /** @class */ (function (_super) {
  71715. __extends(OculusTouchController, _super);
  71716. /**
  71717. * Creates a new OculusTouchController from a gamepad
  71718. * @param vrGamepad the gamepad that the controller should be created from
  71719. */
  71720. function OculusTouchController(vrGamepad) {
  71721. var _this = _super.call(this, vrGamepad) || this;
  71722. /**
  71723. * Fired when the secondary trigger on this controller is modified
  71724. */
  71725. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71726. /**
  71727. * Fired when the thumb rest on this controller is modified
  71728. */
  71729. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71730. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71731. return _this;
  71732. }
  71733. /**
  71734. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71735. * @param scene scene in which to add meshes
  71736. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71737. */
  71738. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71739. var _this = this;
  71740. var meshName;
  71741. // Hand
  71742. if (this.hand === 'left') {
  71743. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71744. }
  71745. else { // Right is the default if no hand is specified
  71746. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71747. }
  71748. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71749. /*
  71750. Parent Mesh name: oculus_touch_left
  71751. - body
  71752. - trigger
  71753. - thumbstick
  71754. - grip
  71755. - button_y
  71756. - button_x
  71757. - button_enter
  71758. */
  71759. _this._defaultModel = newMeshes[1];
  71760. _this.attachToMesh(_this._defaultModel);
  71761. if (meshLoaded) {
  71762. meshLoaded(_this._defaultModel);
  71763. }
  71764. });
  71765. };
  71766. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71767. /**
  71768. * Fired when the A button on this controller is modified
  71769. */
  71770. get: function () {
  71771. if (this.hand === 'right') {
  71772. return this.onMainButtonStateChangedObservable;
  71773. }
  71774. else {
  71775. throw new Error('No A button on left hand');
  71776. }
  71777. },
  71778. enumerable: true,
  71779. configurable: true
  71780. });
  71781. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71782. /**
  71783. * Fired when the B button on this controller is modified
  71784. */
  71785. get: function () {
  71786. if (this.hand === 'right') {
  71787. return this.onSecondaryButtonStateChangedObservable;
  71788. }
  71789. else {
  71790. throw new Error('No B button on left hand');
  71791. }
  71792. },
  71793. enumerable: true,
  71794. configurable: true
  71795. });
  71796. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71797. /**
  71798. * Fired when the X button on this controller is modified
  71799. */
  71800. get: function () {
  71801. if (this.hand === 'left') {
  71802. return this.onMainButtonStateChangedObservable;
  71803. }
  71804. else {
  71805. throw new Error('No X button on right hand');
  71806. }
  71807. },
  71808. enumerable: true,
  71809. configurable: true
  71810. });
  71811. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71812. /**
  71813. * Fired when the Y button on this controller is modified
  71814. */
  71815. get: function () {
  71816. if (this.hand === 'left') {
  71817. return this.onSecondaryButtonStateChangedObservable;
  71818. }
  71819. else {
  71820. throw new Error('No Y button on right hand');
  71821. }
  71822. },
  71823. enumerable: true,
  71824. configurable: true
  71825. });
  71826. /**
  71827. * Called once for each button that changed state since the last frame
  71828. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71829. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71830. * 2) secondary trigger (same)
  71831. * 3) A (right) X (left), touch, pressed = value
  71832. * 4) B / Y
  71833. * 5) thumb rest
  71834. * @param buttonIdx Which button index changed
  71835. * @param state New state of the button
  71836. * @param changes Which properties on the state changed since last frame
  71837. */
  71838. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71839. var notifyObject = state; //{ state: state, changes: changes };
  71840. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71841. switch (buttonIdx) {
  71842. case 0:
  71843. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71844. return;
  71845. case 1: // index trigger
  71846. if (this._defaultModel) {
  71847. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71848. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71849. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71850. }
  71851. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71852. return;
  71853. case 2: // secondary trigger
  71854. if (this._defaultModel) {
  71855. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71856. }
  71857. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71858. return;
  71859. case 3:
  71860. if (this._defaultModel) {
  71861. if (notifyObject.pressed) {
  71862. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71863. }
  71864. else {
  71865. (this._defaultModel.getChildren()[1]).position.y = 0;
  71866. }
  71867. }
  71868. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71869. return;
  71870. case 4:
  71871. if (this._defaultModel) {
  71872. if (notifyObject.pressed) {
  71873. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71874. }
  71875. else {
  71876. (this._defaultModel.getChildren()[2]).position.y = 0;
  71877. }
  71878. }
  71879. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71880. return;
  71881. case 5:
  71882. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71883. return;
  71884. }
  71885. };
  71886. /**
  71887. * Base Url for the controller model.
  71888. */
  71889. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71890. /**
  71891. * File name for the left controller model.
  71892. */
  71893. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71894. /**
  71895. * File name for the right controller model.
  71896. */
  71897. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71898. return OculusTouchController;
  71899. }(BABYLON.WebVRController));
  71900. BABYLON.OculusTouchController = OculusTouchController;
  71901. })(BABYLON || (BABYLON = {}));
  71902. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71903. var BABYLON;
  71904. (function (BABYLON) {
  71905. /**
  71906. * Vive Controller
  71907. */
  71908. var ViveController = /** @class */ (function (_super) {
  71909. __extends(ViveController, _super);
  71910. /**
  71911. * Creates a new ViveController from a gamepad
  71912. * @param vrGamepad the gamepad that the controller should be created from
  71913. */
  71914. function ViveController(vrGamepad) {
  71915. var _this = _super.call(this, vrGamepad) || this;
  71916. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71917. _this._invertLeftStickY = true;
  71918. return _this;
  71919. }
  71920. /**
  71921. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71922. * @param scene scene in which to add meshes
  71923. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71924. */
  71925. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71926. var _this = this;
  71927. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71928. /*
  71929. Parent Mesh name: ViveWand
  71930. - body
  71931. - r_gripper
  71932. - l_gripper
  71933. - menu_button
  71934. - system_button
  71935. - trackpad
  71936. - trigger
  71937. - LED
  71938. */
  71939. _this._defaultModel = newMeshes[1];
  71940. _this.attachToMesh(_this._defaultModel);
  71941. if (meshLoaded) {
  71942. meshLoaded(_this._defaultModel);
  71943. }
  71944. });
  71945. };
  71946. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71947. /**
  71948. * Fired when the left button on this controller is modified
  71949. */
  71950. get: function () {
  71951. return this.onMainButtonStateChangedObservable;
  71952. },
  71953. enumerable: true,
  71954. configurable: true
  71955. });
  71956. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71957. /**
  71958. * Fired when the right button on this controller is modified
  71959. */
  71960. get: function () {
  71961. return this.onMainButtonStateChangedObservable;
  71962. },
  71963. enumerable: true,
  71964. configurable: true
  71965. });
  71966. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71967. /**
  71968. * Fired when the menu button on this controller is modified
  71969. */
  71970. get: function () {
  71971. return this.onSecondaryButtonStateChangedObservable;
  71972. },
  71973. enumerable: true,
  71974. configurable: true
  71975. });
  71976. /**
  71977. * Called once for each button that changed state since the last frame
  71978. * Vive mapping:
  71979. * 0: touchpad
  71980. * 1: trigger
  71981. * 2: left AND right buttons
  71982. * 3: menu button
  71983. * @param buttonIdx Which button index changed
  71984. * @param state New state of the button
  71985. * @param changes Which properties on the state changed since last frame
  71986. */
  71987. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71988. var notifyObject = state; //{ state: state, changes: changes };
  71989. switch (buttonIdx) {
  71990. case 0:
  71991. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71992. return;
  71993. case 1: // index trigger
  71994. if (this._defaultModel) {
  71995. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71996. }
  71997. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71998. return;
  71999. case 2: // left AND right button
  72000. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72001. return;
  72002. case 3:
  72003. if (this._defaultModel) {
  72004. if (notifyObject.pressed) {
  72005. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72006. }
  72007. else {
  72008. (this._defaultModel.getChildren()[2]).position.y = 0;
  72009. }
  72010. }
  72011. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72012. return;
  72013. }
  72014. };
  72015. /**
  72016. * Base Url for the controller model.
  72017. */
  72018. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72019. /**
  72020. * File name for the controller model.
  72021. */
  72022. ViveController.MODEL_FILENAME = 'wand.babylon';
  72023. return ViveController;
  72024. }(BABYLON.WebVRController));
  72025. BABYLON.ViveController = ViveController;
  72026. })(BABYLON || (BABYLON = {}));
  72027. //# sourceMappingURL=babylon.viveController.js.map
  72028. var BABYLON;
  72029. (function (BABYLON) {
  72030. /**
  72031. * Generic Controller
  72032. */
  72033. var GenericController = /** @class */ (function (_super) {
  72034. __extends(GenericController, _super);
  72035. /**
  72036. * Creates a new GenericController from a gamepad
  72037. * @param vrGamepad the gamepad that the controller should be created from
  72038. */
  72039. function GenericController(vrGamepad) {
  72040. return _super.call(this, vrGamepad) || this;
  72041. }
  72042. /**
  72043. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72044. * @param scene scene in which to add meshes
  72045. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72046. */
  72047. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72048. var _this = this;
  72049. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72050. _this._defaultModel = newMeshes[1];
  72051. _this.attachToMesh(_this._defaultModel);
  72052. if (meshLoaded) {
  72053. meshLoaded(_this._defaultModel);
  72054. }
  72055. });
  72056. };
  72057. /**
  72058. * Called once for each button that changed state since the last frame
  72059. * @param buttonIdx Which button index changed
  72060. * @param state New state of the button
  72061. * @param changes Which properties on the state changed since last frame
  72062. */
  72063. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72064. console.log("Button id: " + buttonIdx + "state: ");
  72065. console.dir(state);
  72066. };
  72067. /**
  72068. * Base Url for the controller model.
  72069. */
  72070. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72071. /**
  72072. * File name for the controller model.
  72073. */
  72074. GenericController.MODEL_FILENAME = 'generic.babylon';
  72075. return GenericController;
  72076. }(BABYLON.WebVRController));
  72077. BABYLON.GenericController = GenericController;
  72078. })(BABYLON || (BABYLON = {}));
  72079. //# sourceMappingURL=babylon.genericController.js.map
  72080. var BABYLON;
  72081. (function (BABYLON) {
  72082. /**
  72083. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72084. */
  72085. var LoadedMeshInfo = /** @class */ (function () {
  72086. function LoadedMeshInfo() {
  72087. /**
  72088. * Map of the button meshes contained in the controller
  72089. */
  72090. this.buttonMeshes = {};
  72091. /**
  72092. * Map of the axis meshes contained in the controller
  72093. */
  72094. this.axisMeshes = {};
  72095. }
  72096. return LoadedMeshInfo;
  72097. }());
  72098. /**
  72099. * Defines the WindowsMotionController object that the state of the windows motion controller
  72100. */
  72101. var WindowsMotionController = /** @class */ (function (_super) {
  72102. __extends(WindowsMotionController, _super);
  72103. /**
  72104. * Creates a new WindowsMotionController from a gamepad
  72105. * @param vrGamepad the gamepad that the controller should be created from
  72106. */
  72107. function WindowsMotionController(vrGamepad) {
  72108. var _this = _super.call(this, vrGamepad) || this;
  72109. _this._mapping = {
  72110. // Semantic button names
  72111. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72112. // A mapping of the button name to glTF model node name
  72113. // that should be transformed by button value.
  72114. buttonMeshNames: {
  72115. 'trigger': 'SELECT',
  72116. 'menu': 'MENU',
  72117. 'grip': 'GRASP',
  72118. 'thumbstick': 'THUMBSTICK_PRESS',
  72119. 'trackpad': 'TOUCHPAD_PRESS'
  72120. },
  72121. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72122. buttonObservableNames: {
  72123. 'trigger': 'onTriggerStateChangedObservable',
  72124. 'menu': 'onSecondaryButtonStateChangedObservable',
  72125. 'grip': 'onMainButtonStateChangedObservable',
  72126. 'thumbstick': 'onPadStateChangedObservable',
  72127. 'trackpad': 'onTrackpadChangedObservable'
  72128. },
  72129. // A mapping of the axis name to glTF model node name
  72130. // that should be transformed by axis value.
  72131. // This array mirrors the browserGamepad.axes array, such that
  72132. // the mesh corresponding to axis 0 is in this array index 0.
  72133. axisMeshNames: [
  72134. 'THUMBSTICK_X',
  72135. 'THUMBSTICK_Y',
  72136. 'TOUCHPAD_TOUCH_X',
  72137. 'TOUCHPAD_TOUCH_Y'
  72138. ],
  72139. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72140. };
  72141. /**
  72142. * Fired when the trackpad on this controller is clicked
  72143. */
  72144. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72145. /**
  72146. * Fired when the trackpad on this controller is modified
  72147. */
  72148. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72149. /**
  72150. * The current x and y values of this controller's trackpad
  72151. */
  72152. _this.trackpad = { x: 0, y: 0 };
  72153. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72154. _this._loadedMeshInfo = null;
  72155. return _this;
  72156. }
  72157. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72158. /**
  72159. * Fired when the trigger on this controller is modified
  72160. */
  72161. get: function () {
  72162. return this.onTriggerStateChangedObservable;
  72163. },
  72164. enumerable: true,
  72165. configurable: true
  72166. });
  72167. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72168. /**
  72169. * Fired when the menu button on this controller is modified
  72170. */
  72171. get: function () {
  72172. return this.onSecondaryButtonStateChangedObservable;
  72173. },
  72174. enumerable: true,
  72175. configurable: true
  72176. });
  72177. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72178. /**
  72179. * Fired when the grip button on this controller is modified
  72180. */
  72181. get: function () {
  72182. return this.onMainButtonStateChangedObservable;
  72183. },
  72184. enumerable: true,
  72185. configurable: true
  72186. });
  72187. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72188. /**
  72189. * Fired when the thumbstick button on this controller is modified
  72190. */
  72191. get: function () {
  72192. return this.onPadStateChangedObservable;
  72193. },
  72194. enumerable: true,
  72195. configurable: true
  72196. });
  72197. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72198. /**
  72199. * Fired when the touchpad button on this controller is modified
  72200. */
  72201. get: function () {
  72202. return this.onTrackpadChangedObservable;
  72203. },
  72204. enumerable: true,
  72205. configurable: true
  72206. });
  72207. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72208. /**
  72209. * Fired when the touchpad values on this controller are modified
  72210. */
  72211. get: function () {
  72212. return this.onTrackpadValuesChangedObservable;
  72213. },
  72214. enumerable: true,
  72215. configurable: true
  72216. });
  72217. /**
  72218. * Called once per frame by the engine.
  72219. */
  72220. WindowsMotionController.prototype.update = function () {
  72221. _super.prototype.update.call(this);
  72222. if (this.browserGamepad.axes) {
  72223. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  72224. this.trackpad.x = this.browserGamepad["axes"][2];
  72225. this.trackpad.y = this.browserGamepad["axes"][3];
  72226. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72227. }
  72228. // Only need to animate axes if there is a loaded mesh
  72229. if (this._loadedMeshInfo) {
  72230. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72231. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72232. }
  72233. }
  72234. }
  72235. };
  72236. /**
  72237. * Called once for each button that changed state since the last frame
  72238. * @param buttonIdx Which button index changed
  72239. * @param state New state of the button
  72240. * @param changes Which properties on the state changed since last frame
  72241. */
  72242. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72243. var buttonName = this._mapping.buttons[buttonIdx];
  72244. if (!buttonName) {
  72245. return;
  72246. }
  72247. // Only emit events for buttons that we know how to map from index to name
  72248. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72249. if (observable) {
  72250. observable.notifyObservers(state);
  72251. }
  72252. this._lerpButtonTransform(buttonName, state.value);
  72253. };
  72254. /**
  72255. * Moves the buttons on the controller mesh based on their current state
  72256. * @param buttonName the name of the button to move
  72257. * @param buttonValue the value of the button which determines the buttons new position
  72258. */
  72259. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72260. // If there is no loaded mesh, there is nothing to transform.
  72261. if (!this._loadedMeshInfo) {
  72262. return;
  72263. }
  72264. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72265. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72266. return;
  72267. }
  72268. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72269. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72270. };
  72271. /**
  72272. * Moves the axis on the controller mesh based on its current state
  72273. * @param axis the index of the axis
  72274. * @param axisValue the value of the axis which determines the meshes new position
  72275. * @hidden
  72276. */
  72277. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72278. if (!this._loadedMeshInfo) {
  72279. return;
  72280. }
  72281. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72282. if (!meshInfo) {
  72283. return;
  72284. }
  72285. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72286. return;
  72287. }
  72288. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72289. var lerpValue = axisValue * 0.5 + 0.5;
  72290. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72291. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72292. };
  72293. /**
  72294. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72295. * @param scene scene in which to add meshes
  72296. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72297. */
  72298. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72299. var _this = this;
  72300. if (forceDefault === void 0) { forceDefault = false; }
  72301. var path;
  72302. var filename;
  72303. // Checking if GLB loader is present
  72304. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72305. // Determine the device specific folder based on the ID suffix
  72306. var device = 'default';
  72307. if (this.id && !forceDefault) {
  72308. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72309. device = ((match && match[0]) || device);
  72310. }
  72311. // Hand
  72312. if (this.hand === 'left') {
  72313. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72314. }
  72315. else { // Right is the default if no hand is specified
  72316. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72317. }
  72318. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72319. }
  72320. else {
  72321. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72322. path = BABYLON.GenericController.MODEL_BASE_URL;
  72323. filename = BABYLON.GenericController.MODEL_FILENAME;
  72324. }
  72325. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72326. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72327. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72328. if (!_this._loadedMeshInfo) {
  72329. return;
  72330. }
  72331. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72332. _this.attachToMesh(_this._defaultModel);
  72333. if (meshLoaded) {
  72334. meshLoaded(_this._defaultModel);
  72335. }
  72336. }, null, function (scene, message) {
  72337. BABYLON.Tools.Log(message);
  72338. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72339. if (!forceDefault) {
  72340. _this.initControllerMesh(scene, meshLoaded, true);
  72341. }
  72342. });
  72343. };
  72344. /**
  72345. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72346. * can be transformed by button presses and axes values, based on this._mapping.
  72347. *
  72348. * @param scene scene in which the meshes exist
  72349. * @param meshes list of meshes that make up the controller model to process
  72350. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72351. */
  72352. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72353. var loadedMeshInfo = null;
  72354. // Create a new mesh to contain the glTF hierarchy
  72355. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72356. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72357. var childMesh = null;
  72358. for (var i = 0; i < meshes.length; i++) {
  72359. var mesh = meshes[i];
  72360. if (!mesh.parent) {
  72361. // Exclude controller meshes from picking results
  72362. mesh.isPickable = false;
  72363. // Handle root node, attach to the new parentMesh
  72364. childMesh = mesh;
  72365. break;
  72366. }
  72367. }
  72368. if (childMesh) {
  72369. childMesh.setParent(parentMesh);
  72370. // Create our mesh info. Note that this method will always return non-null.
  72371. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72372. }
  72373. else {
  72374. BABYLON.Tools.Warn('Could not find root node in model file.');
  72375. }
  72376. return loadedMeshInfo;
  72377. };
  72378. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72379. var loadedMeshInfo = new LoadedMeshInfo();
  72380. var i;
  72381. loadedMeshInfo.rootNode = rootNode;
  72382. // Reset the caches
  72383. loadedMeshInfo.buttonMeshes = {};
  72384. loadedMeshInfo.axisMeshes = {};
  72385. // Button Meshes
  72386. for (i = 0; i < this._mapping.buttons.length; i++) {
  72387. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72388. if (!buttonMeshName) {
  72389. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72390. continue;
  72391. }
  72392. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72393. if (!buttonMesh) {
  72394. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72395. continue;
  72396. }
  72397. var buttonMeshInfo = {
  72398. index: i,
  72399. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72400. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72401. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72402. };
  72403. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72404. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72405. }
  72406. else {
  72407. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72408. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72409. '(VALUE: ' + !!buttonMeshInfo.value +
  72410. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72411. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72412. ')');
  72413. }
  72414. }
  72415. // Axis Meshes
  72416. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72417. var axisMeshName = this._mapping.axisMeshNames[i];
  72418. if (!axisMeshName) {
  72419. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72420. continue;
  72421. }
  72422. var axisMesh = getChildByName(rootNode, axisMeshName);
  72423. if (!axisMesh) {
  72424. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72425. continue;
  72426. }
  72427. var axisMeshInfo = {
  72428. index: i,
  72429. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72430. min: getImmediateChildByName(axisMesh, 'MIN'),
  72431. max: getImmediateChildByName(axisMesh, 'MAX')
  72432. };
  72433. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72434. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72435. }
  72436. else {
  72437. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72438. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72439. '(VALUE: ' + !!axisMeshInfo.value +
  72440. ', MIN: ' + !!axisMeshInfo.min +
  72441. ', MAX:' + !!axisMeshInfo.max +
  72442. ')');
  72443. }
  72444. }
  72445. // Pointing Ray
  72446. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72447. if (!loadedMeshInfo.pointingPoseNode) {
  72448. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72449. }
  72450. return loadedMeshInfo;
  72451. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72452. function getChildByName(node, name) {
  72453. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72454. }
  72455. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72456. function getImmediateChildByName(node, name) {
  72457. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72458. }
  72459. };
  72460. /**
  72461. * Gets the ray of the controller in the direction the controller is pointing
  72462. * @param length the length the resulting ray should be
  72463. * @returns a ray in the direction the controller is pointing
  72464. */
  72465. WindowsMotionController.prototype.getForwardRay = function (length) {
  72466. if (length === void 0) { length = 100; }
  72467. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72468. return _super.prototype.getForwardRay.call(this, length);
  72469. }
  72470. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72471. var origin = m.getTranslation();
  72472. var forward = new BABYLON.Vector3(0, 0, -1);
  72473. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72474. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72475. return new BABYLON.Ray(origin, direction, length);
  72476. };
  72477. /**
  72478. * Disposes of the controller
  72479. */
  72480. WindowsMotionController.prototype.dispose = function () {
  72481. _super.prototype.dispose.call(this);
  72482. this.onTrackpadChangedObservable.clear();
  72483. };
  72484. /**
  72485. * The base url used to load the left and right controller models
  72486. */
  72487. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72488. /**
  72489. * The name of the left controller model file
  72490. */
  72491. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72492. /**
  72493. * The name of the right controller model file
  72494. */
  72495. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72496. /**
  72497. * The controller name prefix for this controller type
  72498. */
  72499. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72500. /**
  72501. * The controller id pattern for this controller type
  72502. */
  72503. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72504. return WindowsMotionController;
  72505. }(BABYLON.WebVRController));
  72506. BABYLON.WindowsMotionController = WindowsMotionController;
  72507. })(BABYLON || (BABYLON = {}));
  72508. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72509. var BABYLON;
  72510. (function (BABYLON) {
  72511. /**
  72512. * Gear VR Controller
  72513. */
  72514. var GearVRController = /** @class */ (function (_super) {
  72515. __extends(GearVRController, _super);
  72516. /**
  72517. * Creates a new GearVRController from a gamepad
  72518. * @param vrGamepad the gamepad that the controller should be created from
  72519. */
  72520. function GearVRController(vrGamepad) {
  72521. var _this = _super.call(this, vrGamepad) || this;
  72522. _this._buttonIndexToObservableNameMap = [
  72523. 'onTrackpadChangedObservable',
  72524. 'onTriggerStateChangedObservable' // Trigger
  72525. ];
  72526. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72527. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72528. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72529. return _this;
  72530. }
  72531. /**
  72532. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72533. * @param scene scene in which to add meshes
  72534. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72535. */
  72536. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72537. var _this = this;
  72538. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72539. _this._defaultModel = newMeshes[1];
  72540. _this.attachToMesh(_this._defaultModel);
  72541. if (meshLoaded) {
  72542. meshLoaded(_this._defaultModel);
  72543. }
  72544. });
  72545. };
  72546. /**
  72547. * Called once for each button that changed state since the last frame
  72548. * @param buttonIdx Which button index changed
  72549. * @param state New state of the button
  72550. * @param changes Which properties on the state changed since last frame
  72551. */
  72552. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72553. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72554. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72555. // Only emit events for buttons that we know how to map from index to observable
  72556. var observable = this[observableName];
  72557. if (observable) {
  72558. observable.notifyObservers(state);
  72559. }
  72560. }
  72561. };
  72562. /**
  72563. * Base Url for the controller model.
  72564. */
  72565. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72566. /**
  72567. * File name for the controller model.
  72568. */
  72569. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72570. /**
  72571. * Gamepad Id prefix used to identify this controller.
  72572. */
  72573. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72574. return GearVRController;
  72575. }(BABYLON.WebVRController));
  72576. BABYLON.GearVRController = GearVRController;
  72577. })(BABYLON || (BABYLON = {}));
  72578. //# sourceMappingURL=babylon.gearVRController.js.map
  72579. var BABYLON;
  72580. (function (BABYLON) {
  72581. /**
  72582. * Google Daydream controller
  72583. */
  72584. var DaydreamController = /** @class */ (function (_super) {
  72585. __extends(DaydreamController, _super);
  72586. /**
  72587. * Creates a new DaydreamController from a gamepad
  72588. * @param vrGamepad the gamepad that the controller should be created from
  72589. */
  72590. function DaydreamController(vrGamepad) {
  72591. var _this = _super.call(this, vrGamepad) || this;
  72592. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72593. return _this;
  72594. }
  72595. /**
  72596. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72597. * @param scene scene in which to add meshes
  72598. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72599. */
  72600. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72601. var _this = this;
  72602. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72603. _this._defaultModel = newMeshes[1];
  72604. _this.attachToMesh(_this._defaultModel);
  72605. if (meshLoaded) {
  72606. meshLoaded(_this._defaultModel);
  72607. }
  72608. });
  72609. };
  72610. /**
  72611. * Called once for each button that changed state since the last frame
  72612. * @param buttonIdx Which button index changed
  72613. * @param state New state of the button
  72614. * @param changes Which properties on the state changed since last frame
  72615. */
  72616. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72617. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72618. if (buttonIdx === 0) {
  72619. var observable = this.onTriggerStateChangedObservable;
  72620. if (observable) {
  72621. observable.notifyObservers(state);
  72622. }
  72623. }
  72624. else {
  72625. // If the app or home buttons are ever made available
  72626. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72627. }
  72628. };
  72629. /**
  72630. * Base Url for the controller model.
  72631. */
  72632. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72633. /**
  72634. * File name for the controller model.
  72635. */
  72636. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72637. /**
  72638. * Gamepad Id prefix used to identify Daydream Controller.
  72639. */
  72640. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72641. return DaydreamController;
  72642. }(BABYLON.WebVRController));
  72643. BABYLON.DaydreamController = DaydreamController;
  72644. })(BABYLON || (BABYLON = {}));
  72645. //# sourceMappingURL=babylon.daydreamController.js.map
  72646. var BABYLON;
  72647. (function (BABYLON) {
  72648. var FollowCamera = /** @class */ (function (_super) {
  72649. __extends(FollowCamera, _super);
  72650. function FollowCamera(name, position, scene, lockedTarget) {
  72651. if (lockedTarget === void 0) { lockedTarget = null; }
  72652. var _this = _super.call(this, name, position, scene) || this;
  72653. _this.radius = 12;
  72654. _this.rotationOffset = 0;
  72655. _this.heightOffset = 4;
  72656. _this.cameraAcceleration = 0.05;
  72657. _this.maxCameraSpeed = 20;
  72658. _this.lockedTarget = lockedTarget;
  72659. return _this;
  72660. }
  72661. FollowCamera.prototype.getRadians = function (degrees) {
  72662. return degrees * Math.PI / 180;
  72663. };
  72664. FollowCamera.prototype.follow = function (cameraTarget) {
  72665. if (!cameraTarget)
  72666. return;
  72667. var yRotation;
  72668. if (cameraTarget.rotationQuaternion) {
  72669. var rotMatrix = new BABYLON.Matrix();
  72670. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72671. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72672. }
  72673. else {
  72674. yRotation = cameraTarget.rotation.y;
  72675. }
  72676. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72677. var targetPosition = cameraTarget.getAbsolutePosition();
  72678. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72679. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72680. var dx = targetX - this.position.x;
  72681. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72682. var dz = (targetZ) - this.position.z;
  72683. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72684. var vy = dy * this.cameraAcceleration;
  72685. var vz = dz * this.cameraAcceleration * 2;
  72686. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72687. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72688. }
  72689. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72690. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72691. }
  72692. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72693. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72694. }
  72695. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72696. this.setTarget(targetPosition);
  72697. };
  72698. FollowCamera.prototype._checkInputs = function () {
  72699. _super.prototype._checkInputs.call(this);
  72700. if (this.lockedTarget) {
  72701. this.follow(this.lockedTarget);
  72702. }
  72703. };
  72704. FollowCamera.prototype.getClassName = function () {
  72705. return "FollowCamera";
  72706. };
  72707. __decorate([
  72708. BABYLON.serialize()
  72709. ], FollowCamera.prototype, "radius", void 0);
  72710. __decorate([
  72711. BABYLON.serialize()
  72712. ], FollowCamera.prototype, "rotationOffset", void 0);
  72713. __decorate([
  72714. BABYLON.serialize()
  72715. ], FollowCamera.prototype, "heightOffset", void 0);
  72716. __decorate([
  72717. BABYLON.serialize()
  72718. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72719. __decorate([
  72720. BABYLON.serialize()
  72721. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72722. __decorate([
  72723. BABYLON.serializeAsMeshReference("lockedTargetId")
  72724. ], FollowCamera.prototype, "lockedTarget", void 0);
  72725. return FollowCamera;
  72726. }(BABYLON.TargetCamera));
  72727. BABYLON.FollowCamera = FollowCamera;
  72728. var ArcFollowCamera = /** @class */ (function (_super) {
  72729. __extends(ArcFollowCamera, _super);
  72730. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72731. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72732. _this.alpha = alpha;
  72733. _this.beta = beta;
  72734. _this.radius = radius;
  72735. _this.target = target;
  72736. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72737. _this.follow();
  72738. return _this;
  72739. }
  72740. ArcFollowCamera.prototype.follow = function () {
  72741. if (!this.target) {
  72742. return;
  72743. }
  72744. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72745. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72746. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72747. var targetPosition = this.target.getAbsolutePosition();
  72748. this.position = targetPosition.add(this._cartesianCoordinates);
  72749. this.setTarget(targetPosition);
  72750. };
  72751. ArcFollowCamera.prototype._checkInputs = function () {
  72752. _super.prototype._checkInputs.call(this);
  72753. this.follow();
  72754. };
  72755. ArcFollowCamera.prototype.getClassName = function () {
  72756. return "ArcFollowCamera";
  72757. };
  72758. return ArcFollowCamera;
  72759. }(BABYLON.TargetCamera));
  72760. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72761. })(BABYLON || (BABYLON = {}));
  72762. //# sourceMappingURL=babylon.followCamera.js.map
  72763. var BABYLON;
  72764. (function (BABYLON) {
  72765. // We're mainly based on the logic defined into the FreeCamera code
  72766. var UniversalCamera = /** @class */ (function (_super) {
  72767. __extends(UniversalCamera, _super);
  72768. //-- end properties for backward compatibility for inputs
  72769. function UniversalCamera(name, position, scene) {
  72770. var _this = _super.call(this, name, position, scene) || this;
  72771. _this.inputs.addGamepad();
  72772. return _this;
  72773. }
  72774. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72775. //-- Begin properties for backward compatibility for inputs
  72776. get: function () {
  72777. var gamepad = this.inputs.attached["gamepad"];
  72778. if (gamepad)
  72779. return gamepad.gamepadAngularSensibility;
  72780. return 0;
  72781. },
  72782. set: function (value) {
  72783. var gamepad = this.inputs.attached["gamepad"];
  72784. if (gamepad)
  72785. gamepad.gamepadAngularSensibility = value;
  72786. },
  72787. enumerable: true,
  72788. configurable: true
  72789. });
  72790. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72791. get: function () {
  72792. var gamepad = this.inputs.attached["gamepad"];
  72793. if (gamepad)
  72794. return gamepad.gamepadMoveSensibility;
  72795. return 0;
  72796. },
  72797. set: function (value) {
  72798. var gamepad = this.inputs.attached["gamepad"];
  72799. if (gamepad)
  72800. gamepad.gamepadMoveSensibility = value;
  72801. },
  72802. enumerable: true,
  72803. configurable: true
  72804. });
  72805. UniversalCamera.prototype.getClassName = function () {
  72806. return "UniversalCamera";
  72807. };
  72808. return UniversalCamera;
  72809. }(BABYLON.TouchCamera));
  72810. BABYLON.UniversalCamera = UniversalCamera;
  72811. })(BABYLON || (BABYLON = {}));
  72812. //# sourceMappingURL=babylon.universalCamera.js.map
  72813. var BABYLON;
  72814. (function (BABYLON) {
  72815. // We're mainly based on the logic defined into the FreeCamera code
  72816. var GamepadCamera = /** @class */ (function (_super) {
  72817. __extends(GamepadCamera, _super);
  72818. //-- end properties for backward compatibility for inputs
  72819. function GamepadCamera(name, position, scene) {
  72820. return _super.call(this, name, position, scene) || this;
  72821. }
  72822. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72823. //-- Begin properties for backward compatibility for inputs
  72824. get: function () {
  72825. var gamepad = this.inputs.attached["gamepad"];
  72826. if (gamepad)
  72827. return gamepad.gamepadAngularSensibility;
  72828. return 0;
  72829. },
  72830. set: function (value) {
  72831. var gamepad = this.inputs.attached["gamepad"];
  72832. if (gamepad)
  72833. gamepad.gamepadAngularSensibility = value;
  72834. },
  72835. enumerable: true,
  72836. configurable: true
  72837. });
  72838. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72839. get: function () {
  72840. var gamepad = this.inputs.attached["gamepad"];
  72841. if (gamepad)
  72842. return gamepad.gamepadMoveSensibility;
  72843. return 0;
  72844. },
  72845. set: function (value) {
  72846. var gamepad = this.inputs.attached["gamepad"];
  72847. if (gamepad)
  72848. gamepad.gamepadMoveSensibility = value;
  72849. },
  72850. enumerable: true,
  72851. configurable: true
  72852. });
  72853. GamepadCamera.prototype.getClassName = function () {
  72854. return "GamepadCamera";
  72855. };
  72856. return GamepadCamera;
  72857. }(BABYLON.UniversalCamera));
  72858. BABYLON.GamepadCamera = GamepadCamera;
  72859. })(BABYLON || (BABYLON = {}));
  72860. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72861. var BABYLON;
  72862. (function (BABYLON) {
  72863. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72864. function PostProcessRenderPipelineManager() {
  72865. this._renderPipelines = {};
  72866. }
  72867. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72868. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72869. };
  72870. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72871. if (unique === void 0) { unique = false; }
  72872. var renderPipeline = this._renderPipelines[renderPipelineName];
  72873. if (!renderPipeline) {
  72874. return;
  72875. }
  72876. renderPipeline._attachCameras(cameras, unique);
  72877. };
  72878. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72879. var renderPipeline = this._renderPipelines[renderPipelineName];
  72880. if (!renderPipeline) {
  72881. return;
  72882. }
  72883. renderPipeline._detachCameras(cameras);
  72884. };
  72885. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72886. var renderPipeline = this._renderPipelines[renderPipelineName];
  72887. if (!renderPipeline) {
  72888. return;
  72889. }
  72890. renderPipeline._enableEffect(renderEffectName, cameras);
  72891. };
  72892. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72893. var renderPipeline = this._renderPipelines[renderPipelineName];
  72894. if (!renderPipeline) {
  72895. return;
  72896. }
  72897. renderPipeline._disableEffect(renderEffectName, cameras);
  72898. };
  72899. PostProcessRenderPipelineManager.prototype.update = function () {
  72900. for (var renderPipelineName in this._renderPipelines) {
  72901. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72902. var pipeline = this._renderPipelines[renderPipelineName];
  72903. if (!pipeline.isSupported) {
  72904. pipeline.dispose();
  72905. delete this._renderPipelines[renderPipelineName];
  72906. }
  72907. else {
  72908. pipeline._update();
  72909. }
  72910. }
  72911. }
  72912. };
  72913. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72914. for (var renderPipelineName in this._renderPipelines) {
  72915. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72916. var pipeline = this._renderPipelines[renderPipelineName];
  72917. pipeline._rebuild();
  72918. }
  72919. }
  72920. };
  72921. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72922. for (var renderPipelineName in this._renderPipelines) {
  72923. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72924. var pipeline = this._renderPipelines[renderPipelineName];
  72925. pipeline.dispose();
  72926. }
  72927. }
  72928. };
  72929. return PostProcessRenderPipelineManager;
  72930. }());
  72931. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72932. })(BABYLON || (BABYLON = {}));
  72933. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72934. var BABYLON;
  72935. (function (BABYLON) {
  72936. /**
  72937. * This represents a set of one or more post processes in Babylon.
  72938. * A post process can be used to apply a shader to a texture after it is rendered.
  72939. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72940. */
  72941. var PostProcessRenderEffect = /** @class */ (function () {
  72942. /**
  72943. * Instantiates a post process render effect.
  72944. * A post process can be used to apply a shader to a texture after it is rendered.
  72945. * @param engine The engine the effect is tied to
  72946. * @param name The name of the effect
  72947. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72948. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72949. */
  72950. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72951. this._name = name;
  72952. this._singleInstance = singleInstance || true;
  72953. this._getPostProcesses = getPostProcesses;
  72954. this._cameras = {};
  72955. this._indicesForCamera = {};
  72956. this._postProcesses = {};
  72957. }
  72958. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72959. /**
  72960. * Checks if all the post processes in the effect are supported.
  72961. */
  72962. get: function () {
  72963. for (var index in this._postProcesses) {
  72964. if (this._postProcesses.hasOwnProperty(index)) {
  72965. var pps = this._postProcesses[index];
  72966. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72967. if (!pps[ppIndex].isSupported) {
  72968. return false;
  72969. }
  72970. }
  72971. }
  72972. }
  72973. return true;
  72974. },
  72975. enumerable: true,
  72976. configurable: true
  72977. });
  72978. /**
  72979. * Updates the current state of the effect
  72980. */
  72981. PostProcessRenderEffect.prototype._update = function () {
  72982. };
  72983. /**
  72984. * Attaches the effect on cameras
  72985. * @param cameras The camera to attach to.
  72986. */
  72987. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72988. var _this = this;
  72989. var cameraKey;
  72990. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72991. if (!cams) {
  72992. return;
  72993. }
  72994. for (var i = 0; i < cams.length; i++) {
  72995. var camera = cams[i];
  72996. var cameraName = camera.name;
  72997. if (this._singleInstance) {
  72998. cameraKey = 0;
  72999. }
  73000. else {
  73001. cameraKey = cameraName;
  73002. }
  73003. if (!this._postProcesses[cameraKey]) {
  73004. var postProcess = this._getPostProcesses();
  73005. if (postProcess) {
  73006. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73007. }
  73008. }
  73009. if (!this._indicesForCamera[cameraName]) {
  73010. this._indicesForCamera[cameraName] = [];
  73011. }
  73012. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73013. var index = camera.attachPostProcess(postProcess);
  73014. _this._indicesForCamera[cameraName].push(index);
  73015. });
  73016. if (!this._cameras[cameraName]) {
  73017. this._cameras[cameraName] = camera;
  73018. }
  73019. }
  73020. };
  73021. /**
  73022. * Detatches the effect on cameras
  73023. * @param cameras The camera to detatch from.
  73024. */
  73025. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73026. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73027. if (!cams) {
  73028. return;
  73029. }
  73030. for (var i = 0; i < cams.length; i++) {
  73031. var camera = cams[i];
  73032. var cameraName = camera.name;
  73033. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73034. camera.detachPostProcess(postProcess);
  73035. });
  73036. if (this._cameras[cameraName]) {
  73037. //this._indicesForCamera.splice(index, 1);
  73038. this._cameras[cameraName] = null;
  73039. }
  73040. }
  73041. };
  73042. /**
  73043. * Enables the effect on given cameras
  73044. * @param cameras The camera to enable.
  73045. */
  73046. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73047. var _this = this;
  73048. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73049. if (!cams) {
  73050. return;
  73051. }
  73052. for (var i = 0; i < cams.length; i++) {
  73053. var camera = cams[i];
  73054. var cameraName = camera.name;
  73055. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73056. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73057. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73058. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73059. });
  73060. }
  73061. }
  73062. }
  73063. };
  73064. /**
  73065. * Disables the effect on the given cameras
  73066. * @param cameras The camera to disable.
  73067. */
  73068. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73069. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73070. if (!cams) {
  73071. return;
  73072. }
  73073. for (var i = 0; i < cams.length; i++) {
  73074. var camera = cams[i];
  73075. var cameraName = camera.name;
  73076. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73077. camera.detachPostProcess(postProcess);
  73078. });
  73079. }
  73080. };
  73081. /**
  73082. * Gets a list of the post processes contained in the effect.
  73083. * @param camera The camera to get the post processes on.
  73084. * @returns The list of the post processes in the effect.
  73085. */
  73086. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73087. if (this._singleInstance) {
  73088. return this._postProcesses[0];
  73089. }
  73090. else {
  73091. if (!camera) {
  73092. return null;
  73093. }
  73094. return this._postProcesses[camera.name];
  73095. }
  73096. };
  73097. return PostProcessRenderEffect;
  73098. }());
  73099. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73100. })(BABYLON || (BABYLON = {}));
  73101. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73102. var BABYLON;
  73103. (function (BABYLON) {
  73104. var PostProcessRenderPipeline = /** @class */ (function () {
  73105. function PostProcessRenderPipeline(engine, name) {
  73106. this.engine = engine;
  73107. this._name = name;
  73108. this._renderEffects = {};
  73109. this._renderEffectsForIsolatedPass = new Array();
  73110. this._cameras = [];
  73111. }
  73112. PostProcessRenderPipeline.prototype.getClassName = function () {
  73113. return "PostProcessRenderPipeline";
  73114. };
  73115. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73116. get: function () {
  73117. for (var renderEffectName in this._renderEffects) {
  73118. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73119. if (!this._renderEffects[renderEffectName].isSupported) {
  73120. return false;
  73121. }
  73122. }
  73123. }
  73124. return true;
  73125. },
  73126. enumerable: true,
  73127. configurable: true
  73128. });
  73129. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73130. this._renderEffects[renderEffect._name] = renderEffect;
  73131. };
  73132. // private
  73133. PostProcessRenderPipeline.prototype._rebuild = function () {
  73134. };
  73135. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73136. var renderEffects = this._renderEffects[renderEffectName];
  73137. if (!renderEffects) {
  73138. return;
  73139. }
  73140. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73141. };
  73142. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73143. var renderEffects = this._renderEffects[renderEffectName];
  73144. if (!renderEffects) {
  73145. return;
  73146. }
  73147. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73148. };
  73149. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73150. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73151. if (!cams) {
  73152. return;
  73153. }
  73154. var indicesToDelete = [];
  73155. var i;
  73156. for (i = 0; i < cams.length; i++) {
  73157. var camera = cams[i];
  73158. var cameraName = camera.name;
  73159. if (this._cameras.indexOf(camera) === -1) {
  73160. this._cameras[cameraName] = camera;
  73161. }
  73162. else if (unique) {
  73163. indicesToDelete.push(i);
  73164. }
  73165. }
  73166. for (i = 0; i < indicesToDelete.length; i++) {
  73167. cameras.splice(indicesToDelete[i], 1);
  73168. }
  73169. for (var renderEffectName in this._renderEffects) {
  73170. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73171. this._renderEffects[renderEffectName]._attachCameras(cams);
  73172. }
  73173. }
  73174. };
  73175. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73176. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73177. if (!cams) {
  73178. return;
  73179. }
  73180. for (var renderEffectName in this._renderEffects) {
  73181. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73182. this._renderEffects[renderEffectName]._detachCameras(cams);
  73183. }
  73184. }
  73185. for (var i = 0; i < cams.length; i++) {
  73186. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73187. }
  73188. };
  73189. PostProcessRenderPipeline.prototype._update = function () {
  73190. for (var renderEffectName in this._renderEffects) {
  73191. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73192. this._renderEffects[renderEffectName]._update();
  73193. }
  73194. }
  73195. for (var i = 0; i < this._cameras.length; i++) {
  73196. var cameraName = this._cameras[i].name;
  73197. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73198. this._renderEffectsForIsolatedPass[cameraName]._update();
  73199. }
  73200. }
  73201. };
  73202. PostProcessRenderPipeline.prototype._reset = function () {
  73203. this._renderEffects = {};
  73204. this._renderEffectsForIsolatedPass = new Array();
  73205. };
  73206. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73207. // 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)
  73208. var effectKeys = Object.keys(this._renderEffects);
  73209. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73210. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73211. if (postProcesses) {
  73212. postProcesses[0].samples = sampleCount;
  73213. return true;
  73214. }
  73215. }
  73216. return false;
  73217. };
  73218. PostProcessRenderPipeline.prototype.dispose = function () {
  73219. // Must be implemented by children
  73220. };
  73221. __decorate([
  73222. BABYLON.serialize()
  73223. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73224. return PostProcessRenderPipeline;
  73225. }());
  73226. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73227. })(BABYLON || (BABYLON = {}));
  73228. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73229. var BABYLON;
  73230. (function (BABYLON) {
  73231. /**
  73232. * This represents a depth renderer in Babylon.
  73233. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73234. */
  73235. var DepthRenderer = /** @class */ (function () {
  73236. /**
  73237. * Instantiates a depth renderer
  73238. * @param scene The scene the renderer belongs to
  73239. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73240. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73241. */
  73242. function DepthRenderer(scene, type, camera) {
  73243. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73244. if (camera === void 0) { camera = null; }
  73245. var _this = this;
  73246. this._scene = scene;
  73247. this._camera = camera;
  73248. var engine = scene.getEngine();
  73249. // Render target
  73250. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73251. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73252. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73253. this._depthMap.refreshRate = 1;
  73254. this._depthMap.renderParticles = false;
  73255. this._depthMap.renderList = null;
  73256. // Camera to get depth map from to support multiple concurrent cameras
  73257. this._depthMap.activeCamera = this._camera;
  73258. this._depthMap.ignoreCameraViewport = true;
  73259. this._depthMap.useCameraPostProcesses = false;
  73260. // set default depth value to 1.0 (far away)
  73261. this._depthMap.onClearObservable.add(function (engine) {
  73262. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73263. });
  73264. // Custom render function
  73265. var renderSubMesh = function (subMesh) {
  73266. var mesh = subMesh.getRenderingMesh();
  73267. var scene = _this._scene;
  73268. var engine = scene.getEngine();
  73269. var material = subMesh.getMaterial();
  73270. if (!material) {
  73271. return;
  73272. }
  73273. // Culling and reverse (right handed system)
  73274. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73275. // Managing instances
  73276. var batch = mesh._getInstancesRenderList(subMesh._id);
  73277. if (batch.mustReturn) {
  73278. return;
  73279. }
  73280. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73281. var camera = _this._camera || scene.activeCamera;
  73282. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73283. engine.enableEffect(_this._effect);
  73284. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73285. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73286. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73287. // Alpha test
  73288. if (material && material.needAlphaTesting()) {
  73289. var alphaTexture = material.getAlphaTestTexture();
  73290. if (alphaTexture) {
  73291. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73292. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73293. }
  73294. }
  73295. // Bones
  73296. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73297. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73298. }
  73299. // Draw
  73300. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73301. }
  73302. };
  73303. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73304. var index;
  73305. if (depthOnlySubMeshes.length) {
  73306. engine.setColorWrite(false);
  73307. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73308. renderSubMesh(depthOnlySubMeshes.data[index]);
  73309. }
  73310. engine.setColorWrite(true);
  73311. }
  73312. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73313. renderSubMesh(opaqueSubMeshes.data[index]);
  73314. }
  73315. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73316. renderSubMesh(alphaTestSubMeshes.data[index]);
  73317. }
  73318. };
  73319. }
  73320. /**
  73321. * Creates the depth rendering effect and checks if the effect is ready.
  73322. * @param subMesh The submesh to be used to render the depth map of
  73323. * @param useInstances If multiple world instances should be used
  73324. * @returns if the depth renderer is ready to render the depth map
  73325. */
  73326. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73327. var material = subMesh.getMaterial();
  73328. if (material.disableDepthWrite) {
  73329. return false;
  73330. }
  73331. var defines = [];
  73332. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73333. var mesh = subMesh.getMesh();
  73334. // Alpha test
  73335. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73336. defines.push("#define ALPHATEST");
  73337. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73338. attribs.push(BABYLON.VertexBuffer.UVKind);
  73339. defines.push("#define UV1");
  73340. }
  73341. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73342. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73343. defines.push("#define UV2");
  73344. }
  73345. }
  73346. // Bones
  73347. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73348. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73349. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73350. if (mesh.numBoneInfluencers > 4) {
  73351. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73352. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73353. }
  73354. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73355. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73356. }
  73357. else {
  73358. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73359. }
  73360. // Instances
  73361. if (useInstances) {
  73362. defines.push("#define INSTANCES");
  73363. attribs.push("world0");
  73364. attribs.push("world1");
  73365. attribs.push("world2");
  73366. attribs.push("world3");
  73367. }
  73368. // Get correct effect
  73369. var join = defines.join("\n");
  73370. if (this._cachedDefines !== join) {
  73371. this._cachedDefines = join;
  73372. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73373. }
  73374. return this._effect.isReady();
  73375. };
  73376. /**
  73377. * Gets the texture which the depth map will be written to.
  73378. * @returns The depth map texture
  73379. */
  73380. DepthRenderer.prototype.getDepthMap = function () {
  73381. return this._depthMap;
  73382. };
  73383. /**
  73384. * Disposes of the depth renderer.
  73385. */
  73386. DepthRenderer.prototype.dispose = function () {
  73387. this._depthMap.dispose();
  73388. };
  73389. return DepthRenderer;
  73390. }());
  73391. BABYLON.DepthRenderer = DepthRenderer;
  73392. })(BABYLON || (BABYLON = {}));
  73393. //# sourceMappingURL=babylon.depthRenderer.js.map
  73394. var BABYLON;
  73395. (function (BABYLON) {
  73396. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73397. __extends(SSAORenderingPipeline, _super);
  73398. /**
  73399. * @constructor
  73400. * @param {string} name - The rendering pipeline name
  73401. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73402. * @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 }
  73403. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73404. */
  73405. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73406. var _this = _super.call(this, scene.getEngine(), name) || this;
  73407. // Members
  73408. /**
  73409. * The PassPostProcess id in the pipeline that contains the original scene color
  73410. */
  73411. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73412. /**
  73413. * The SSAO PostProcess id in the pipeline
  73414. */
  73415. _this.SSAORenderEffect = "SSAORenderEffect";
  73416. /**
  73417. * The horizontal blur PostProcess id in the pipeline
  73418. */
  73419. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73420. /**
  73421. * The vertical blur PostProcess id in the pipeline
  73422. */
  73423. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73424. /**
  73425. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73426. */
  73427. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73428. /**
  73429. * The output strength of the SSAO post-process. Default value is 1.0.
  73430. */
  73431. _this.totalStrength = 1.0;
  73432. /**
  73433. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73434. */
  73435. _this.radius = 0.0001;
  73436. /**
  73437. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73438. * Must not be equal to fallOff and superior to fallOff.
  73439. * Default value is 0.975
  73440. */
  73441. _this.area = 0.0075;
  73442. /**
  73443. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73444. * Must not be equal to area and inferior to area.
  73445. * Default value is 0.0
  73446. */
  73447. _this.fallOff = 0.000001;
  73448. /**
  73449. * The base color of the SSAO post-process
  73450. * The final result is "base + ssao" between [0, 1]
  73451. */
  73452. _this.base = 0.5;
  73453. _this._firstUpdate = true;
  73454. _this._scene = scene;
  73455. // Set up assets
  73456. _this._createRandomTexture();
  73457. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73458. var ssaoRatio = ratio.ssaoRatio || ratio;
  73459. var combineRatio = ratio.combineRatio || ratio;
  73460. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73461. _this._createSSAOPostProcess(ssaoRatio);
  73462. _this._createBlurPostProcess(ssaoRatio);
  73463. _this._createSSAOCombinePostProcess(combineRatio);
  73464. // Set up pipeline
  73465. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73466. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73467. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73468. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73469. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73470. // Finish
  73471. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73472. if (cameras)
  73473. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73474. return _this;
  73475. }
  73476. // Public Methods
  73477. /**
  73478. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73479. */
  73480. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73481. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73482. for (var i = 0; i < this._scene.cameras.length; i++) {
  73483. var camera = this._scene.cameras[i];
  73484. this._originalColorPostProcess.dispose(camera);
  73485. this._ssaoPostProcess.dispose(camera);
  73486. this._blurHPostProcess.dispose(camera);
  73487. this._blurVPostProcess.dispose(camera);
  73488. this._ssaoCombinePostProcess.dispose(camera);
  73489. }
  73490. this._randomTexture.dispose();
  73491. if (disableDepthRender)
  73492. this._scene.disableDepthRenderer();
  73493. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73494. _super.prototype.dispose.call(this);
  73495. };
  73496. // Private Methods
  73497. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73498. var _this = this;
  73499. var size = 16;
  73500. 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);
  73501. 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);
  73502. this._blurHPostProcess.onActivateObservable.add(function () {
  73503. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73504. _this._blurHPostProcess.kernel = size * dw;
  73505. });
  73506. this._blurVPostProcess.onActivateObservable.add(function () {
  73507. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73508. _this._blurVPostProcess.kernel = size * dw;
  73509. });
  73510. };
  73511. SSAORenderingPipeline.prototype._rebuild = function () {
  73512. this._firstUpdate = true;
  73513. _super.prototype._rebuild.call(this);
  73514. };
  73515. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73516. var _this = this;
  73517. var numSamples = 16;
  73518. var sampleSphere = [
  73519. 0.5381, 0.1856, -0.4319,
  73520. 0.1379, 0.2486, 0.4430,
  73521. 0.3371, 0.5679, -0.0057,
  73522. -0.6999, -0.0451, -0.0019,
  73523. 0.0689, -0.1598, -0.8547,
  73524. 0.0560, 0.0069, -0.1843,
  73525. -0.0146, 0.1402, 0.0762,
  73526. 0.0100, -0.1924, -0.0344,
  73527. -0.3577, -0.5301, -0.4358,
  73528. -0.3169, 0.1063, 0.0158,
  73529. 0.0103, -0.5869, 0.0046,
  73530. -0.0897, -0.4940, 0.3287,
  73531. 0.7119, -0.0154, -0.0918,
  73532. -0.0533, 0.0596, -0.5411,
  73533. 0.0352, -0.0631, 0.5460,
  73534. -0.4776, 0.2847, -0.0271
  73535. ];
  73536. var samplesFactor = 1.0 / numSamples;
  73537. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73538. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73539. "area", "fallOff", "base", "range", "viewport"
  73540. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73541. this._ssaoPostProcess.onApply = function (effect) {
  73542. if (_this._firstUpdate) {
  73543. effect.setArray3("sampleSphere", sampleSphere);
  73544. effect.setFloat("samplesFactor", samplesFactor);
  73545. effect.setFloat("randTextureTiles", 4.0);
  73546. }
  73547. effect.setFloat("totalStrength", _this.totalStrength);
  73548. effect.setFloat("radius", _this.radius);
  73549. effect.setFloat("area", _this.area);
  73550. effect.setFloat("fallOff", _this.fallOff);
  73551. effect.setFloat("base", _this.base);
  73552. effect.setTexture("textureSampler", _this._depthTexture);
  73553. effect.setTexture("randomSampler", _this._randomTexture);
  73554. };
  73555. };
  73556. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73557. var _this = this;
  73558. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73559. this._ssaoCombinePostProcess.onApply = function (effect) {
  73560. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73561. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73562. };
  73563. };
  73564. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73565. var size = 512;
  73566. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73567. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73568. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73569. var context = this._randomTexture.getContext();
  73570. var rand = function (min, max) {
  73571. return Math.random() * (max - min) + min;
  73572. };
  73573. var randVector = BABYLON.Vector3.Zero();
  73574. for (var x = 0; x < size; x++) {
  73575. for (var y = 0; y < size; y++) {
  73576. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73577. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73578. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73579. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73580. context.fillRect(x, y, 1, 1);
  73581. }
  73582. }
  73583. this._randomTexture.update(false);
  73584. };
  73585. __decorate([
  73586. BABYLON.serialize()
  73587. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73588. __decorate([
  73589. BABYLON.serialize()
  73590. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73591. __decorate([
  73592. BABYLON.serialize()
  73593. ], SSAORenderingPipeline.prototype, "area", void 0);
  73594. __decorate([
  73595. BABYLON.serialize()
  73596. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73597. __decorate([
  73598. BABYLON.serialize()
  73599. ], SSAORenderingPipeline.prototype, "base", void 0);
  73600. return SSAORenderingPipeline;
  73601. }(BABYLON.PostProcessRenderPipeline));
  73602. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73603. })(BABYLON || (BABYLON = {}));
  73604. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73605. var BABYLON;
  73606. (function (BABYLON) {
  73607. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73608. __extends(SSAO2RenderingPipeline, _super);
  73609. /**
  73610. * @constructor
  73611. * @param {string} name - The rendering pipeline name
  73612. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73613. * @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 }
  73614. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73615. */
  73616. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73617. var _this = _super.call(this, scene.getEngine(), name) || this;
  73618. // Members
  73619. /**
  73620. * The PassPostProcess id in the pipeline that contains the original scene color
  73621. */
  73622. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73623. /**
  73624. * The SSAO PostProcess id in the pipeline
  73625. */
  73626. _this.SSAORenderEffect = "SSAORenderEffect";
  73627. /**
  73628. * The horizontal blur PostProcess id in the pipeline
  73629. */
  73630. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73631. /**
  73632. * The vertical blur PostProcess id in the pipeline
  73633. */
  73634. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73635. /**
  73636. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73637. */
  73638. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73639. /**
  73640. * The output strength of the SSAO post-process. Default value is 1.0.
  73641. */
  73642. _this.totalStrength = 1.0;
  73643. /**
  73644. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73645. */
  73646. _this.maxZ = 100.0;
  73647. /**
  73648. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73649. */
  73650. _this.minZAspect = 0.2;
  73651. /**
  73652. * Number of samples used for the SSAO calculations. Default value is 8
  73653. */
  73654. _this._samples = 8;
  73655. /**
  73656. * Are we using bilateral blur ?
  73657. */
  73658. _this._expensiveBlur = true;
  73659. /**
  73660. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73661. */
  73662. _this.radius = 2.0;
  73663. /**
  73664. * The base color of the SSAO post-process
  73665. * The final result is "base + ssao" between [0, 1]
  73666. */
  73667. _this.base = 0.1;
  73668. _this._firstUpdate = true;
  73669. _this._scene = scene;
  73670. _this._ratio = ratio;
  73671. if (!_this.isSupported) {
  73672. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73673. return _this;
  73674. }
  73675. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73676. var blurRatio = _this._ratio.blurRatio || ratio;
  73677. // Set up assets
  73678. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73679. _this._createRandomTexture();
  73680. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73681. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73682. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73683. _this._createSSAOPostProcess(1.0);
  73684. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73685. _this._createSSAOCombinePostProcess(blurRatio);
  73686. // Set up pipeline
  73687. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73688. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73689. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73690. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73691. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73692. // Finish
  73693. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73694. if (cameras)
  73695. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73696. return _this;
  73697. }
  73698. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73699. get: function () {
  73700. return this._samples;
  73701. },
  73702. set: function (n) {
  73703. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73704. this._samples = n;
  73705. this._sampleSphere = this._generateHemisphere();
  73706. this._firstUpdate = true;
  73707. },
  73708. enumerable: true,
  73709. configurable: true
  73710. });
  73711. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73712. get: function () {
  73713. return this._expensiveBlur;
  73714. },
  73715. set: function (b) {
  73716. 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"]);
  73717. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73718. this._expensiveBlur = b;
  73719. this._firstUpdate = true;
  73720. },
  73721. enumerable: true,
  73722. configurable: true
  73723. });
  73724. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73725. /**
  73726. * Support test.
  73727. */
  73728. get: function () {
  73729. var engine = BABYLON.Engine.LastCreatedEngine;
  73730. if (!engine) {
  73731. return false;
  73732. }
  73733. return engine.getCaps().drawBuffersExtension;
  73734. },
  73735. enumerable: true,
  73736. configurable: true
  73737. });
  73738. // Public Methods
  73739. /**
  73740. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73741. */
  73742. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73743. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73744. for (var i = 0; i < this._scene.cameras.length; i++) {
  73745. var camera = this._scene.cameras[i];
  73746. this._originalColorPostProcess.dispose(camera);
  73747. this._ssaoPostProcess.dispose(camera);
  73748. this._blurHPostProcess.dispose(camera);
  73749. this._blurVPostProcess.dispose(camera);
  73750. this._ssaoCombinePostProcess.dispose(camera);
  73751. }
  73752. this._randomTexture.dispose();
  73753. if (disableGeometryBufferRenderer)
  73754. this._scene.disableGeometryBufferRenderer();
  73755. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73756. _super.prototype.dispose.call(this);
  73757. };
  73758. // Private Methods
  73759. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73760. var _this = this;
  73761. this._samplerOffsets = [];
  73762. var expensive = this.expensiveBlur;
  73763. for (var i = -8; i < 8; i++) {
  73764. this._samplerOffsets.push(i * 2 + 0.5);
  73765. }
  73766. 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");
  73767. this._blurHPostProcess.onApply = function (effect) {
  73768. if (!_this._scene.activeCamera) {
  73769. return;
  73770. }
  73771. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73772. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73773. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73774. effect.setFloat("radius", _this.radius);
  73775. effect.setTexture("depthSampler", _this._depthTexture);
  73776. if (_this._firstUpdate) {
  73777. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73778. }
  73779. };
  73780. 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");
  73781. this._blurVPostProcess.onApply = function (effect) {
  73782. if (!_this._scene.activeCamera) {
  73783. return;
  73784. }
  73785. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73786. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73787. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73788. effect.setFloat("radius", _this.radius);
  73789. effect.setTexture("depthSampler", _this._depthTexture);
  73790. if (_this._firstUpdate) {
  73791. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73792. _this._firstUpdate = false;
  73793. }
  73794. };
  73795. };
  73796. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73797. this._firstUpdate = true;
  73798. _super.prototype._rebuild.call(this);
  73799. };
  73800. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73801. var numSamples = this.samples;
  73802. var result = [];
  73803. var vector, scale;
  73804. var rand = function (min, max) {
  73805. return Math.random() * (max - min) + min;
  73806. };
  73807. var i = 0;
  73808. while (i < numSamples) {
  73809. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73810. vector.normalize();
  73811. scale = i / numSamples;
  73812. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73813. vector.scaleInPlace(scale);
  73814. result.push(vector.x, vector.y, vector.z);
  73815. i++;
  73816. }
  73817. return result;
  73818. };
  73819. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73820. var _this = this;
  73821. var numSamples = this.samples;
  73822. this._sampleSphere = this._generateHemisphere();
  73823. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73824. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73825. "base", "range", "projection", "near", "far", "texelSize",
  73826. "xViewport", "yViewport", "maxZ", "minZAspect"
  73827. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73828. this._ssaoPostProcess.onApply = function (effect) {
  73829. if (_this._firstUpdate) {
  73830. effect.setArray3("sampleSphere", _this._sampleSphere);
  73831. effect.setFloat("randTextureTiles", 4.0);
  73832. }
  73833. if (!_this._scene.activeCamera) {
  73834. return;
  73835. }
  73836. effect.setFloat("samplesFactor", 1 / _this.samples);
  73837. effect.setFloat("totalStrength", _this.totalStrength);
  73838. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73839. effect.setFloat("radius", _this.radius);
  73840. effect.setFloat("maxZ", _this.maxZ);
  73841. effect.setFloat("minZAspect", _this.minZAspect);
  73842. effect.setFloat("base", _this.base);
  73843. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73844. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73845. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73846. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73847. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73848. effect.setTexture("textureSampler", _this._depthTexture);
  73849. effect.setTexture("normalSampler", _this._normalTexture);
  73850. effect.setTexture("randomSampler", _this._randomTexture);
  73851. };
  73852. };
  73853. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73854. var _this = this;
  73855. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73856. this._ssaoCombinePostProcess.onApply = function (effect) {
  73857. var viewport = _this._scene.activeCamera.viewport;
  73858. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73859. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73860. };
  73861. };
  73862. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73863. var size = 512;
  73864. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73865. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73866. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73867. var context = this._randomTexture.getContext();
  73868. var rand = function (min, max) {
  73869. return Math.random() * (max - min) + min;
  73870. };
  73871. var randVector = BABYLON.Vector3.Zero();
  73872. for (var x = 0; x < size; x++) {
  73873. for (var y = 0; y < size; y++) {
  73874. randVector.x = rand(0.0, 1.0);
  73875. randVector.y = rand(0.0, 1.0);
  73876. randVector.z = 0.0;
  73877. randVector.normalize();
  73878. randVector.scaleInPlace(255);
  73879. randVector.x = Math.floor(randVector.x);
  73880. randVector.y = Math.floor(randVector.y);
  73881. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73882. context.fillRect(x, y, 1, 1);
  73883. }
  73884. }
  73885. this._randomTexture.update(false);
  73886. };
  73887. /**
  73888. * Serialize the rendering pipeline (Used when exporting)
  73889. * @returns the serialized object
  73890. */
  73891. SSAO2RenderingPipeline.prototype.serialize = function () {
  73892. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73893. serializationObject.customType = "SSAO2RenderingPipeline";
  73894. return serializationObject;
  73895. };
  73896. /**
  73897. * Parse the serialized pipeline
  73898. * @param source Source pipeline.
  73899. * @param scene The scene to load the pipeline to.
  73900. * @param rootUrl The URL of the serialized pipeline.
  73901. * @returns An instantiated pipeline from the serialized object.
  73902. */
  73903. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73904. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73905. };
  73906. __decorate([
  73907. BABYLON.serialize()
  73908. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73909. __decorate([
  73910. BABYLON.serialize()
  73911. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73912. __decorate([
  73913. BABYLON.serialize()
  73914. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73915. __decorate([
  73916. BABYLON.serialize("samples")
  73917. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73918. __decorate([
  73919. BABYLON.serialize()
  73920. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73921. __decorate([
  73922. BABYLON.serialize("expensiveBlur")
  73923. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73924. __decorate([
  73925. BABYLON.serialize()
  73926. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73927. __decorate([
  73928. BABYLON.serialize()
  73929. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73930. return SSAO2RenderingPipeline;
  73931. }(BABYLON.PostProcessRenderPipeline));
  73932. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73933. })(BABYLON || (BABYLON = {}));
  73934. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73935. // BABYLON.JS Chromatic Aberration GLSL Shader
  73936. // Author: Olivier Guyot
  73937. // Separates very slightly R, G and B colors on the edges of the screen
  73938. // Inspired by Francois Tarlier & Martins Upitis
  73939. var BABYLON;
  73940. (function (BABYLON) {
  73941. var LensRenderingPipeline = /** @class */ (function (_super) {
  73942. __extends(LensRenderingPipeline, _super);
  73943. /**
  73944. * @constructor
  73945. *
  73946. * Effect parameters are as follow:
  73947. * {
  73948. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73949. * edge_blur: number; // from 0 to x (1 for realism)
  73950. * distortion: number; // from 0 to x (1 for realism)
  73951. * grain_amount: number; // from 0 to 1
  73952. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73953. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73954. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73955. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73956. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73957. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73958. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73959. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73960. * }
  73961. * Note: if an effect parameter is unset, effect is disabled
  73962. *
  73963. * @param {string} name - The rendering pipeline name
  73964. * @param {object} parameters - An object containing all parameters (see above)
  73965. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73966. * @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)
  73967. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73968. */
  73969. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73970. if (ratio === void 0) { ratio = 1.0; }
  73971. var _this = _super.call(this, scene.getEngine(), name) || this;
  73972. // Lens effects can be of the following:
  73973. // - chromatic aberration (slight shift of RGB colors)
  73974. // - blur on the edge of the lens
  73975. // - lens distortion
  73976. // - depth-of-field blur & highlights enhancing
  73977. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73978. // - grain effect (noise or custom texture)
  73979. // Two additional texture samplers are needed:
  73980. // - depth map (for depth-of-field)
  73981. // - grain texture
  73982. /**
  73983. * The chromatic aberration PostProcess id in the pipeline
  73984. */
  73985. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73986. /**
  73987. * The highlights enhancing PostProcess id in the pipeline
  73988. */
  73989. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73990. /**
  73991. * The depth-of-field PostProcess id in the pipeline
  73992. */
  73993. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73994. _this._scene = scene;
  73995. // Fetch texture samplers
  73996. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73997. if (parameters.grain_texture) {
  73998. _this._grainTexture = parameters.grain_texture;
  73999. }
  74000. else {
  74001. _this._createGrainTexture();
  74002. }
  74003. // save parameters
  74004. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74005. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74006. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74007. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74008. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74009. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74010. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74011. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74012. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74013. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74014. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74015. // Create effects
  74016. _this._createChromaticAberrationPostProcess(ratio);
  74017. _this._createHighlightsPostProcess(ratio);
  74018. _this._createDepthOfFieldPostProcess(ratio / 4);
  74019. // Set up pipeline
  74020. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74021. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74022. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74023. if (_this._highlightsGain === -1) {
  74024. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74025. }
  74026. // Finish
  74027. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74028. if (cameras) {
  74029. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74030. }
  74031. return _this;
  74032. }
  74033. // public methods (self explanatory)
  74034. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74035. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74036. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74037. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74038. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74039. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74040. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74041. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74042. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74043. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74044. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74045. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74046. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74047. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74048. };
  74049. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74050. this._highlightsPostProcess.updateEffect();
  74051. };
  74052. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74053. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74054. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74055. this._highlightsGain = amount;
  74056. };
  74057. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74058. if (this._highlightsGain === -1) {
  74059. this._highlightsGain = 1.0;
  74060. }
  74061. this._highlightsThreshold = amount;
  74062. };
  74063. LensRenderingPipeline.prototype.disableHighlights = function () {
  74064. this._highlightsGain = -1;
  74065. };
  74066. /**
  74067. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74068. */
  74069. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74070. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74071. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74072. this._chromaticAberrationPostProcess = null;
  74073. this._highlightsPostProcess = null;
  74074. this._depthOfFieldPostProcess = null;
  74075. this._grainTexture.dispose();
  74076. if (disableDepthRender)
  74077. this._scene.disableDepthRenderer();
  74078. };
  74079. // colors shifting and distortion
  74080. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74081. var _this = this;
  74082. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74083. [], // samplers
  74084. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74085. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74086. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74087. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74088. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74089. effect.setFloat('radialIntensity', 1);
  74090. effect.setFloat2('direction', 17, 17);
  74091. effect.setFloat2('centerPosition', 0.5, 0.5);
  74092. };
  74093. };
  74094. // highlights enhancing
  74095. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74096. var _this = this;
  74097. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74098. [], // samplers
  74099. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74100. this._highlightsPostProcess.onApply = function (effect) {
  74101. effect.setFloat('gain', _this._highlightsGain);
  74102. effect.setFloat('threshold', _this._highlightsThreshold);
  74103. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74104. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74105. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74106. };
  74107. };
  74108. // colors shifting and distortion
  74109. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74110. var _this = this;
  74111. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74112. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74113. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74114. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74115. this._depthOfFieldPostProcess.onApply = function (effect) {
  74116. effect.setTexture("depthSampler", _this._depthTexture);
  74117. effect.setTexture("grainSampler", _this._grainTexture);
  74118. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74119. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74120. effect.setFloat('grain_amount', _this._grainAmount);
  74121. effect.setBool('blur_noise', _this._blurNoise);
  74122. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74123. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74124. effect.setFloat('distortion', _this._distortion);
  74125. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74126. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74127. effect.setFloat('aperture', _this._dofAperture);
  74128. effect.setFloat('darken', _this._dofDarken);
  74129. effect.setFloat('edge_blur', _this._edgeBlur);
  74130. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74131. if (_this._scene.activeCamera) {
  74132. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74133. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74134. }
  74135. };
  74136. };
  74137. // creates a black and white random noise texture, 512x512
  74138. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74139. var size = 512;
  74140. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74141. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74142. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74143. var context = this._grainTexture.getContext();
  74144. var rand = function (min, max) {
  74145. return Math.random() * (max - min) + min;
  74146. };
  74147. var value;
  74148. for (var x = 0; x < size; x++) {
  74149. for (var y = 0; y < size; y++) {
  74150. value = Math.floor(rand(0.42, 0.58) * 255);
  74151. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74152. context.fillRect(x, y, 1, 1);
  74153. }
  74154. }
  74155. this._grainTexture.update(false);
  74156. };
  74157. return LensRenderingPipeline;
  74158. }(BABYLON.PostProcessRenderPipeline));
  74159. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74160. })(BABYLON || (BABYLON = {}));
  74161. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74162. var BABYLON;
  74163. (function (BABYLON) {
  74164. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74165. __extends(StandardRenderingPipeline, _super);
  74166. /**
  74167. * @constructor
  74168. * @param {string} name - The rendering pipeline name
  74169. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74170. * @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)
  74171. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74172. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74173. */
  74174. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74175. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74176. var _this = _super.call(this, scene.getEngine(), name) || this;
  74177. _this.downSampleX4PostProcess = null;
  74178. _this.brightPassPostProcess = null;
  74179. _this.blurHPostProcesses = [];
  74180. _this.blurVPostProcesses = [];
  74181. _this.textureAdderPostProcess = null;
  74182. _this.volumetricLightPostProcess = null;
  74183. _this.volumetricLightSmoothXPostProcess = null;
  74184. _this.volumetricLightSmoothYPostProcess = null;
  74185. _this.volumetricLightMergePostProces = null;
  74186. _this.volumetricLightFinalPostProcess = null;
  74187. _this.luminancePostProcess = null;
  74188. _this.luminanceDownSamplePostProcesses = [];
  74189. _this.hdrPostProcess = null;
  74190. _this.textureAdderFinalPostProcess = null;
  74191. _this.lensFlareFinalPostProcess = null;
  74192. _this.hdrFinalPostProcess = null;
  74193. _this.lensFlarePostProcess = null;
  74194. _this.lensFlareComposePostProcess = null;
  74195. _this.motionBlurPostProcess = null;
  74196. _this.depthOfFieldPostProcess = null;
  74197. // Values
  74198. _this.brightThreshold = 1.0;
  74199. _this.blurWidth = 512.0;
  74200. _this.horizontalBlur = false;
  74201. _this.exposure = 1.0;
  74202. _this.lensTexture = null;
  74203. _this.volumetricLightCoefficient = 0.2;
  74204. _this.volumetricLightPower = 4.0;
  74205. _this.volumetricLightBlurScale = 64.0;
  74206. _this.sourceLight = null;
  74207. _this.hdrMinimumLuminance = 1.0;
  74208. _this.hdrDecreaseRate = 0.5;
  74209. _this.hdrIncreaseRate = 0.5;
  74210. _this.lensColorTexture = null;
  74211. _this.lensFlareStrength = 20.0;
  74212. _this.lensFlareGhostDispersal = 1.4;
  74213. _this.lensFlareHaloWidth = 0.7;
  74214. _this.lensFlareDistortionStrength = 16.0;
  74215. _this.lensStarTexture = null;
  74216. _this.lensFlareDirtTexture = null;
  74217. _this.depthOfFieldDistance = 10.0;
  74218. _this.depthOfFieldBlurWidth = 64.0;
  74219. _this.motionStrength = 1.0;
  74220. // IAnimatable
  74221. _this.animations = [];
  74222. _this._currentDepthOfFieldSource = null;
  74223. _this._hdrCurrentLuminance = 1.0;
  74224. // Getters and setters
  74225. _this._bloomEnabled = true;
  74226. _this._depthOfFieldEnabled = false;
  74227. _this._vlsEnabled = false;
  74228. _this._lensFlareEnabled = false;
  74229. _this._hdrEnabled = false;
  74230. _this._motionBlurEnabled = false;
  74231. _this._motionBlurSamples = 64.0;
  74232. _this._volumetricLightStepsCount = 50.0;
  74233. _this._cameras = cameras || [];
  74234. // Initialize
  74235. _this._scene = scene;
  74236. _this._basePostProcess = originalPostProcess;
  74237. _this._ratio = ratio;
  74238. // Misc
  74239. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74240. // Finish
  74241. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74242. _this._buildPipeline();
  74243. return _this;
  74244. }
  74245. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74246. get: function () {
  74247. return this._bloomEnabled;
  74248. },
  74249. set: function (enabled) {
  74250. if (this._bloomEnabled === enabled) {
  74251. return;
  74252. }
  74253. this._bloomEnabled = enabled;
  74254. this._buildPipeline();
  74255. },
  74256. enumerable: true,
  74257. configurable: true
  74258. });
  74259. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74260. get: function () {
  74261. return this._depthOfFieldEnabled;
  74262. },
  74263. set: function (enabled) {
  74264. if (this._depthOfFieldEnabled === enabled) {
  74265. return;
  74266. }
  74267. this._depthOfFieldEnabled = enabled;
  74268. this._buildPipeline();
  74269. },
  74270. enumerable: true,
  74271. configurable: true
  74272. });
  74273. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74274. get: function () {
  74275. return this._lensFlareEnabled;
  74276. },
  74277. set: function (enabled) {
  74278. if (this._lensFlareEnabled === enabled) {
  74279. return;
  74280. }
  74281. this._lensFlareEnabled = enabled;
  74282. this._buildPipeline();
  74283. },
  74284. enumerable: true,
  74285. configurable: true
  74286. });
  74287. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74288. get: function () {
  74289. return this._hdrEnabled;
  74290. },
  74291. set: function (enabled) {
  74292. if (this._hdrEnabled === enabled) {
  74293. return;
  74294. }
  74295. this._hdrEnabled = enabled;
  74296. this._buildPipeline();
  74297. },
  74298. enumerable: true,
  74299. configurable: true
  74300. });
  74301. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74302. get: function () {
  74303. return this._vlsEnabled;
  74304. },
  74305. set: function (enabled) {
  74306. if (this._vlsEnabled === enabled) {
  74307. return;
  74308. }
  74309. if (enabled) {
  74310. var geometry = this._scene.enableGeometryBufferRenderer();
  74311. if (!geometry) {
  74312. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74313. return;
  74314. }
  74315. }
  74316. this._vlsEnabled = enabled;
  74317. this._buildPipeline();
  74318. },
  74319. enumerable: true,
  74320. configurable: true
  74321. });
  74322. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74323. get: function () {
  74324. return this._motionBlurEnabled;
  74325. },
  74326. set: function (enabled) {
  74327. if (this._motionBlurEnabled === enabled) {
  74328. return;
  74329. }
  74330. this._motionBlurEnabled = enabled;
  74331. this._buildPipeline();
  74332. },
  74333. enumerable: true,
  74334. configurable: true
  74335. });
  74336. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74337. get: function () {
  74338. return this._volumetricLightStepsCount;
  74339. },
  74340. set: function (count) {
  74341. if (this.volumetricLightPostProcess) {
  74342. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74343. }
  74344. this._volumetricLightStepsCount = count;
  74345. },
  74346. enumerable: true,
  74347. configurable: true
  74348. });
  74349. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74350. get: function () {
  74351. return this._motionBlurSamples;
  74352. },
  74353. set: function (samples) {
  74354. if (this.motionBlurPostProcess) {
  74355. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74356. }
  74357. this._motionBlurSamples = samples;
  74358. },
  74359. enumerable: true,
  74360. configurable: true
  74361. });
  74362. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74363. var _this = this;
  74364. var ratio = this._ratio;
  74365. var scene = this._scene;
  74366. this._disposePostProcesses();
  74367. this._reset();
  74368. // Create pass post-process
  74369. if (!this._basePostProcess) {
  74370. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74371. this.originalPostProcess.onApply = function (effect) {
  74372. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74373. };
  74374. }
  74375. else {
  74376. this.originalPostProcess = this._basePostProcess;
  74377. }
  74378. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74379. this._currentDepthOfFieldSource = this.originalPostProcess;
  74380. if (this._bloomEnabled) {
  74381. // Create down sample X4 post-process
  74382. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74383. // Create bright pass post-process
  74384. this._createBrightPassPostProcess(scene, ratio / 2);
  74385. // Create gaussian blur post-processes (down sampling blurs)
  74386. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74387. // Create texture adder post-process
  74388. this._createTextureAdderPostProcess(scene, ratio);
  74389. // Create depth-of-field source post-process
  74390. 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);
  74391. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74392. }
  74393. if (this._vlsEnabled) {
  74394. // Create volumetric light
  74395. this._createVolumetricLightPostProcess(scene, ratio);
  74396. // Create volumetric light final post-process
  74397. 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);
  74398. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74399. }
  74400. if (this._lensFlareEnabled) {
  74401. // Create lens flare post-process
  74402. this._createLensFlarePostProcess(scene, ratio);
  74403. // Create depth-of-field source post-process post lens-flare and disable it now
  74404. 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);
  74405. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74406. }
  74407. if (this._hdrEnabled) {
  74408. // Create luminance
  74409. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74410. // Create HDR
  74411. this._createHdrPostProcess(scene, ratio);
  74412. // Create depth-of-field source post-process post hdr and disable it now
  74413. 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);
  74414. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74415. }
  74416. if (this._depthOfFieldEnabled) {
  74417. // Create gaussian blur used by depth-of-field
  74418. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74419. // Create depth-of-field post-process
  74420. this._createDepthOfFieldPostProcess(scene, ratio);
  74421. }
  74422. if (this._motionBlurEnabled) {
  74423. // Create motion blur post-process
  74424. this._createMotionBlurPostProcess(scene, ratio);
  74425. }
  74426. if (this._cameras !== null) {
  74427. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74428. }
  74429. };
  74430. // Down Sample X4 Post-Processs
  74431. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74432. var _this = this;
  74433. var downSampleX4Offsets = new Array(32);
  74434. 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);
  74435. this.downSampleX4PostProcess.onApply = function (effect) {
  74436. var id = 0;
  74437. var width = _this.downSampleX4PostProcess.width;
  74438. var height = _this.downSampleX4PostProcess.height;
  74439. for (var i = -2; i < 2; i++) {
  74440. for (var j = -2; j < 2; j++) {
  74441. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74442. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74443. id += 2;
  74444. }
  74445. }
  74446. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74447. };
  74448. // Add to pipeline
  74449. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74450. };
  74451. // Brightpass Post-Process
  74452. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74453. var _this = this;
  74454. var brightOffsets = new Array(8);
  74455. 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);
  74456. this.brightPassPostProcess.onApply = function (effect) {
  74457. var sU = (1.0 / _this.brightPassPostProcess.width);
  74458. var sV = (1.0 / _this.brightPassPostProcess.height);
  74459. brightOffsets[0] = -0.5 * sU;
  74460. brightOffsets[1] = 0.5 * sV;
  74461. brightOffsets[2] = 0.5 * sU;
  74462. brightOffsets[3] = 0.5 * sV;
  74463. brightOffsets[4] = -0.5 * sU;
  74464. brightOffsets[5] = -0.5 * sV;
  74465. brightOffsets[6] = 0.5 * sU;
  74466. brightOffsets[7] = -0.5 * sV;
  74467. effect.setArray2("dsOffsets", brightOffsets);
  74468. effect.setFloat("brightThreshold", _this.brightThreshold);
  74469. };
  74470. // Add to pipeline
  74471. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74472. };
  74473. // Create blur H&V post-processes
  74474. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74475. var _this = this;
  74476. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74477. var engine = scene.getEngine();
  74478. 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);
  74479. 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);
  74480. blurX.onActivateObservable.add(function () {
  74481. var dw = blurX.width / engine.getRenderWidth();
  74482. blurX.kernel = _this[blurWidthKey] * dw;
  74483. });
  74484. blurY.onActivateObservable.add(function () {
  74485. var dw = blurY.height / engine.getRenderHeight();
  74486. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74487. });
  74488. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74489. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74490. this.blurHPostProcesses.push(blurX);
  74491. this.blurVPostProcesses.push(blurY);
  74492. };
  74493. // Create texture adder post-process
  74494. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74495. var _this = this;
  74496. 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);
  74497. this.textureAdderPostProcess.onApply = function (effect) {
  74498. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74499. effect.setTexture("lensSampler", _this.lensTexture);
  74500. effect.setFloat("exposure", _this.exposure);
  74501. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74502. };
  74503. // Add to pipeline
  74504. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74505. };
  74506. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74507. var _this = this;
  74508. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74509. geometryRenderer.enablePosition = true;
  74510. var geometry = geometryRenderer.getGBuffer();
  74511. // Base post-process
  74512. 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));
  74513. var depthValues = BABYLON.Vector2.Zero();
  74514. this.volumetricLightPostProcess.onApply = function (effect) {
  74515. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74516. var generator = _this.sourceLight.getShadowGenerator();
  74517. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74518. effect.setTexture("positionSampler", geometry.textures[2]);
  74519. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74520. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74521. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74522. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74523. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74524. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74525. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74526. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74527. effect.setVector2("depthValues", depthValues);
  74528. }
  74529. };
  74530. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74531. // Smooth
  74532. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74533. // Merge
  74534. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74535. this.volumetricLightMergePostProces.onApply = function (effect) {
  74536. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74537. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74538. };
  74539. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74540. };
  74541. // Create luminance
  74542. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74543. var _this = this;
  74544. // Create luminance
  74545. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74546. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74547. var offsets = [];
  74548. this.luminancePostProcess.onApply = function (effect) {
  74549. var sU = (1.0 / _this.luminancePostProcess.width);
  74550. var sV = (1.0 / _this.luminancePostProcess.height);
  74551. offsets[0] = -0.5 * sU;
  74552. offsets[1] = 0.5 * sV;
  74553. offsets[2] = 0.5 * sU;
  74554. offsets[3] = 0.5 * sV;
  74555. offsets[4] = -0.5 * sU;
  74556. offsets[5] = -0.5 * sV;
  74557. offsets[6] = 0.5 * sU;
  74558. offsets[7] = -0.5 * sV;
  74559. effect.setArray2("lumOffsets", offsets);
  74560. };
  74561. // Add to pipeline
  74562. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74563. // Create down sample luminance
  74564. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74565. var size = Math.pow(3, i);
  74566. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74567. if (i === 0) {
  74568. defines += "#define FINAL_DOWN_SAMPLER";
  74569. }
  74570. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74571. this.luminanceDownSamplePostProcesses.push(postProcess);
  74572. }
  74573. // Create callbacks and add effects
  74574. var lastLuminance = this.luminancePostProcess;
  74575. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74576. var downSampleOffsets = new Array(18);
  74577. pp.onApply = function (effect) {
  74578. if (!lastLuminance) {
  74579. return;
  74580. }
  74581. var id = 0;
  74582. for (var x = -1; x < 2; x++) {
  74583. for (var y = -1; y < 2; y++) {
  74584. downSampleOffsets[id] = x / lastLuminance.width;
  74585. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74586. id += 2;
  74587. }
  74588. }
  74589. effect.setArray2("dsOffsets", downSampleOffsets);
  74590. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74591. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74592. lastLuminance = _this.luminancePostProcess;
  74593. }
  74594. else {
  74595. lastLuminance = pp;
  74596. }
  74597. };
  74598. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74599. pp.onAfterRender = function (effect) {
  74600. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74601. 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);
  74602. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74603. };
  74604. }
  74605. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74606. });
  74607. };
  74608. // Create HDR post-process
  74609. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74610. var _this = this;
  74611. 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);
  74612. var outputLiminance = 1;
  74613. var time = 0;
  74614. var lastTime = 0;
  74615. this.hdrPostProcess.onApply = function (effect) {
  74616. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74617. time += scene.getEngine().getDeltaTime();
  74618. if (outputLiminance < 0) {
  74619. outputLiminance = _this._hdrCurrentLuminance;
  74620. }
  74621. else {
  74622. var dt = (lastTime - time) / 1000.0;
  74623. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74624. outputLiminance += _this.hdrDecreaseRate * dt;
  74625. }
  74626. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74627. outputLiminance -= _this.hdrIncreaseRate * dt;
  74628. }
  74629. else {
  74630. outputLiminance = _this._hdrCurrentLuminance;
  74631. }
  74632. }
  74633. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74634. effect.setFloat("averageLuminance", outputLiminance);
  74635. lastTime = time;
  74636. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74637. };
  74638. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74639. };
  74640. // Create lens flare post-process
  74641. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74642. var _this = this;
  74643. 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);
  74644. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74645. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74646. 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);
  74647. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74648. var resolution = new BABYLON.Vector2(0, 0);
  74649. // Lens flare
  74650. this.lensFlarePostProcess.onApply = function (effect) {
  74651. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74652. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74653. effect.setFloat("strength", _this.lensFlareStrength);
  74654. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74655. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74656. // Shift
  74657. resolution.x = _this.lensFlarePostProcess.width;
  74658. resolution.y = _this.lensFlarePostProcess.height;
  74659. effect.setVector2("resolution", resolution);
  74660. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74661. };
  74662. // Compose
  74663. 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);
  74664. 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);
  74665. this.lensFlareComposePostProcess.onApply = function (effect) {
  74666. if (!_this._scene.activeCamera) {
  74667. return;
  74668. }
  74669. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74670. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74671. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74672. // Lens start rotation matrix
  74673. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74674. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74675. 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));
  74676. camRot *= 4.0;
  74677. 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);
  74678. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74679. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74680. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74681. };
  74682. };
  74683. // Create depth-of-field post-process
  74684. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74685. var _this = this;
  74686. 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);
  74687. this.depthOfFieldPostProcess.onApply = function (effect) {
  74688. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74689. effect.setTexture("depthSampler", _this._getDepthTexture());
  74690. effect.setFloat("distance", _this.depthOfFieldDistance);
  74691. };
  74692. // Add to pipeline
  74693. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74694. };
  74695. // Create motion blur post-process
  74696. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74697. var _this = this;
  74698. 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);
  74699. var motionScale = 0;
  74700. var prevViewProjection = BABYLON.Matrix.Identity();
  74701. var invViewProjection = BABYLON.Matrix.Identity();
  74702. var viewProjection = BABYLON.Matrix.Identity();
  74703. var screenSize = BABYLON.Vector2.Zero();
  74704. this.motionBlurPostProcess.onApply = function (effect) {
  74705. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74706. viewProjection.invertToRef(invViewProjection);
  74707. effect.setMatrix("inverseViewProjection", invViewProjection);
  74708. effect.setMatrix("prevViewProjection", prevViewProjection);
  74709. prevViewProjection = viewProjection;
  74710. screenSize.x = _this.motionBlurPostProcess.width;
  74711. screenSize.y = _this.motionBlurPostProcess.height;
  74712. effect.setVector2("screenSize", screenSize);
  74713. motionScale = scene.getEngine().getFps() / 60.0;
  74714. effect.setFloat("motionScale", motionScale);
  74715. effect.setFloat("motionStrength", _this.motionStrength);
  74716. effect.setTexture("depthSampler", _this._getDepthTexture());
  74717. };
  74718. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74719. };
  74720. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74721. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74722. var renderer = this._scene.enableGeometryBufferRenderer();
  74723. return renderer.getGBuffer().textures[0];
  74724. }
  74725. return this._scene.enableDepthRenderer().getDepthMap();
  74726. };
  74727. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74728. for (var i = 0; i < this._cameras.length; i++) {
  74729. var camera = this._cameras[i];
  74730. if (this.originalPostProcess) {
  74731. this.originalPostProcess.dispose(camera);
  74732. }
  74733. if (this.downSampleX4PostProcess) {
  74734. this.downSampleX4PostProcess.dispose(camera);
  74735. }
  74736. if (this.brightPassPostProcess) {
  74737. this.brightPassPostProcess.dispose(camera);
  74738. }
  74739. if (this.textureAdderPostProcess) {
  74740. this.textureAdderPostProcess.dispose(camera);
  74741. }
  74742. if (this.textureAdderFinalPostProcess) {
  74743. this.textureAdderFinalPostProcess.dispose(camera);
  74744. }
  74745. if (this.volumetricLightPostProcess) {
  74746. this.volumetricLightPostProcess.dispose(camera);
  74747. }
  74748. if (this.volumetricLightSmoothXPostProcess) {
  74749. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74750. }
  74751. if (this.volumetricLightSmoothYPostProcess) {
  74752. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74753. }
  74754. if (this.volumetricLightMergePostProces) {
  74755. this.volumetricLightMergePostProces.dispose(camera);
  74756. }
  74757. if (this.volumetricLightFinalPostProcess) {
  74758. this.volumetricLightFinalPostProcess.dispose(camera);
  74759. }
  74760. if (this.lensFlarePostProcess) {
  74761. this.lensFlarePostProcess.dispose(camera);
  74762. }
  74763. if (this.lensFlareComposePostProcess) {
  74764. this.lensFlareComposePostProcess.dispose(camera);
  74765. }
  74766. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74767. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74768. }
  74769. if (this.luminancePostProcess) {
  74770. this.luminancePostProcess.dispose(camera);
  74771. }
  74772. if (this.hdrPostProcess) {
  74773. this.hdrPostProcess.dispose(camera);
  74774. }
  74775. if (this.hdrFinalPostProcess) {
  74776. this.hdrFinalPostProcess.dispose(camera);
  74777. }
  74778. if (this.depthOfFieldPostProcess) {
  74779. this.depthOfFieldPostProcess.dispose(camera);
  74780. }
  74781. if (this.motionBlurPostProcess) {
  74782. this.motionBlurPostProcess.dispose(camera);
  74783. }
  74784. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74785. this.blurHPostProcesses[j].dispose(camera);
  74786. }
  74787. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74788. this.blurVPostProcesses[j].dispose(camera);
  74789. }
  74790. }
  74791. this.originalPostProcess = null;
  74792. this.downSampleX4PostProcess = null;
  74793. this.brightPassPostProcess = null;
  74794. this.textureAdderPostProcess = null;
  74795. this.textureAdderFinalPostProcess = null;
  74796. this.volumetricLightPostProcess = null;
  74797. this.volumetricLightSmoothXPostProcess = null;
  74798. this.volumetricLightSmoothYPostProcess = null;
  74799. this.volumetricLightMergePostProces = null;
  74800. this.volumetricLightFinalPostProcess = null;
  74801. this.lensFlarePostProcess = null;
  74802. this.lensFlareComposePostProcess = null;
  74803. this.luminancePostProcess = null;
  74804. this.hdrPostProcess = null;
  74805. this.hdrFinalPostProcess = null;
  74806. this.depthOfFieldPostProcess = null;
  74807. this.motionBlurPostProcess = null;
  74808. this.luminanceDownSamplePostProcesses = [];
  74809. this.blurHPostProcesses = [];
  74810. this.blurVPostProcesses = [];
  74811. };
  74812. /**
  74813. * Dispose of the pipeline and stop all post processes
  74814. */
  74815. StandardRenderingPipeline.prototype.dispose = function () {
  74816. this._disposePostProcesses();
  74817. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74818. _super.prototype.dispose.call(this);
  74819. };
  74820. /**
  74821. * Serialize the rendering pipeline (Used when exporting)
  74822. * @returns the serialized object
  74823. */
  74824. StandardRenderingPipeline.prototype.serialize = function () {
  74825. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74826. if (this.sourceLight) {
  74827. serializationObject.sourceLightId = this.sourceLight.id;
  74828. }
  74829. serializationObject.customType = "StandardRenderingPipeline";
  74830. return serializationObject;
  74831. };
  74832. /**
  74833. * Parse the serialized pipeline
  74834. * @param source Source pipeline.
  74835. * @param scene The scene to load the pipeline to.
  74836. * @param rootUrl The URL of the serialized pipeline.
  74837. * @returns An instantiated pipeline from the serialized object.
  74838. */
  74839. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74840. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74841. if (source.sourceLightId) {
  74842. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74843. }
  74844. return p;
  74845. };
  74846. // Luminance steps
  74847. StandardRenderingPipeline.LuminanceSteps = 6;
  74848. __decorate([
  74849. BABYLON.serialize()
  74850. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74851. __decorate([
  74852. BABYLON.serialize()
  74853. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74854. __decorate([
  74855. BABYLON.serialize()
  74856. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74857. __decorate([
  74858. BABYLON.serialize()
  74859. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74860. __decorate([
  74861. BABYLON.serializeAsTexture("lensTexture")
  74862. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74863. __decorate([
  74864. BABYLON.serialize()
  74865. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74866. __decorate([
  74867. BABYLON.serialize()
  74868. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74869. __decorate([
  74870. BABYLON.serialize()
  74871. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74872. __decorate([
  74873. BABYLON.serialize()
  74874. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74875. __decorate([
  74876. BABYLON.serialize()
  74877. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74878. __decorate([
  74879. BABYLON.serialize()
  74880. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74881. __decorate([
  74882. BABYLON.serializeAsTexture("lensColorTexture")
  74883. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74884. __decorate([
  74885. BABYLON.serialize()
  74886. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74887. __decorate([
  74888. BABYLON.serialize()
  74889. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74890. __decorate([
  74891. BABYLON.serialize()
  74892. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74893. __decorate([
  74894. BABYLON.serialize()
  74895. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74896. __decorate([
  74897. BABYLON.serializeAsTexture("lensStarTexture")
  74898. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74899. __decorate([
  74900. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74901. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74902. __decorate([
  74903. BABYLON.serialize()
  74904. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74905. __decorate([
  74906. BABYLON.serialize()
  74907. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74908. __decorate([
  74909. BABYLON.serialize()
  74910. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74911. __decorate([
  74912. BABYLON.serialize()
  74913. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74914. __decorate([
  74915. BABYLON.serialize()
  74916. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74917. __decorate([
  74918. BABYLON.serialize()
  74919. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74920. __decorate([
  74921. BABYLON.serialize()
  74922. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74923. __decorate([
  74924. BABYLON.serialize()
  74925. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74926. __decorate([
  74927. BABYLON.serialize()
  74928. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74929. __decorate([
  74930. BABYLON.serialize()
  74931. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74932. __decorate([
  74933. BABYLON.serialize()
  74934. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74935. __decorate([
  74936. BABYLON.serialize()
  74937. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74938. return StandardRenderingPipeline;
  74939. }(BABYLON.PostProcessRenderPipeline));
  74940. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74941. })(BABYLON || (BABYLON = {}));
  74942. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74943. var BABYLON;
  74944. (function (BABYLON) {
  74945. var FxaaPostProcess = /** @class */ (function (_super) {
  74946. __extends(FxaaPostProcess, _super);
  74947. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74948. if (camera === void 0) { camera = null; }
  74949. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74950. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74951. var defines = _this._getDefines();
  74952. _this.updateEffect(defines);
  74953. _this.onApplyObservable.add(function (effect) {
  74954. var texelSize = _this.texelSize;
  74955. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74956. });
  74957. return _this;
  74958. }
  74959. FxaaPostProcess.prototype._getDefines = function () {
  74960. var engine = this.getEngine();
  74961. if (!engine) {
  74962. return null;
  74963. }
  74964. var glInfo = engine.getGlInfo();
  74965. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74966. return "#define MALI 1\n";
  74967. }
  74968. return null;
  74969. };
  74970. return FxaaPostProcess;
  74971. }(BABYLON.PostProcess));
  74972. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74973. })(BABYLON || (BABYLON = {}));
  74974. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74975. var BABYLON;
  74976. (function (BABYLON) {
  74977. /**
  74978. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74979. */
  74980. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74981. __extends(ChromaticAberrationPostProcess, _super);
  74982. /**
  74983. * Creates a new instance ChromaticAberrationPostProcess
  74984. * @param name The name of the effect.
  74985. * @param screenWidth The width of the screen to apply the effect on.
  74986. * @param screenHeight The height of the screen to apply the effect on.
  74987. * @param options The required width/height ratio to downsize to before computing the render pass.
  74988. * @param camera The camera to apply the render pass to.
  74989. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74990. * @param engine The engine which the post process will be applied. (default: current engine)
  74991. * @param reusable If the post process can be reused on the same frame. (default: false)
  74992. * @param textureType Type of textures used when performing the post process. (default: 0)
  74993. * @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)
  74994. */
  74995. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74996. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74997. if (blockCompilation === void 0) { blockCompilation = false; }
  74998. 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;
  74999. /**
  75000. * The amount of seperation of rgb channels (default: 30)
  75001. */
  75002. _this.aberrationAmount = 30;
  75003. /**
  75004. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75005. */
  75006. _this.radialIntensity = 0;
  75007. /**
  75008. * 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))
  75009. */
  75010. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75011. /**
  75012. * 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))
  75013. */
  75014. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75015. _this.onApplyObservable.add(function (effect) {
  75016. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75017. effect.setFloat('screen_width', screenWidth);
  75018. effect.setFloat('screen_height', screenHeight);
  75019. effect.setFloat('radialIntensity', _this.radialIntensity);
  75020. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75021. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75022. });
  75023. return _this;
  75024. }
  75025. return ChromaticAberrationPostProcess;
  75026. }(BABYLON.PostProcess));
  75027. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75028. })(BABYLON || (BABYLON = {}));
  75029. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75030. var BABYLON;
  75031. (function (BABYLON) {
  75032. /**
  75033. * The GrainPostProcess adds noise to the image at mid luminance levels
  75034. */
  75035. var GrainPostProcess = /** @class */ (function (_super) {
  75036. __extends(GrainPostProcess, _super);
  75037. /**
  75038. * Creates a new instance of @see GrainPostProcess
  75039. * @param name The name of the effect.
  75040. * @param options The required width/height ratio to downsize to before computing the render pass.
  75041. * @param camera The camera to apply the render pass to.
  75042. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75043. * @param engine The engine which the post process will be applied. (default: current engine)
  75044. * @param reusable If the post process can be reused on the same frame. (default: false)
  75045. * @param textureType Type of textures used when performing the post process. (default: 0)
  75046. * @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)
  75047. */
  75048. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75049. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75050. if (blockCompilation === void 0) { blockCompilation = false; }
  75051. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75052. /**
  75053. * The intensity of the grain added (default: 30)
  75054. */
  75055. _this.intensity = 30;
  75056. /**
  75057. * If the grain should be randomized on every frame
  75058. */
  75059. _this.animated = false;
  75060. _this.onApplyObservable.add(function (effect) {
  75061. effect.setFloat('intensity', _this.intensity);
  75062. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75063. });
  75064. return _this;
  75065. }
  75066. return GrainPostProcess;
  75067. }(BABYLON.PostProcess));
  75068. BABYLON.GrainPostProcess = GrainPostProcess;
  75069. })(BABYLON || (BABYLON = {}));
  75070. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75071. var BABYLON;
  75072. (function (BABYLON) {
  75073. /**
  75074. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75075. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75076. */
  75077. var SharpenPostProcess = /** @class */ (function (_super) {
  75078. __extends(SharpenPostProcess, _super);
  75079. /**
  75080. * Creates a new instance ConvolutionPostProcess
  75081. * @param name The name of the effect.
  75082. * @param options The required width/height ratio to downsize to before computing the render pass.
  75083. * @param camera The camera to apply the render pass to.
  75084. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75085. * @param engine The engine which the post process will be applied. (default: current engine)
  75086. * @param reusable If the post process can be reused on the same frame. (default: false)
  75087. * @param textureType Type of textures used when performing the post process. (default: 0)
  75088. * @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)
  75089. */
  75090. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75091. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75092. if (blockCompilation === void 0) { blockCompilation = false; }
  75093. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75094. /**
  75095. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75096. */
  75097. _this.colorAmount = 1.0;
  75098. /**
  75099. * How much sharpness should be applied (default: 0.3)
  75100. */
  75101. _this.edgeAmount = 0.3;
  75102. _this.onApply = function (effect) {
  75103. effect.setFloat2("screenSize", _this.width, _this.height);
  75104. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75105. };
  75106. return _this;
  75107. }
  75108. return SharpenPostProcess;
  75109. }(BABYLON.PostProcess));
  75110. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75111. })(BABYLON || (BABYLON = {}));
  75112. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75113. var BABYLON;
  75114. (function (BABYLON) {
  75115. /**
  75116. * The Blur Post Process which blurs an image based on a kernel and direction.
  75117. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75118. */
  75119. var BlurPostProcess = /** @class */ (function (_super) {
  75120. __extends(BlurPostProcess, _super);
  75121. /**
  75122. * Creates a new instance BlurPostProcess
  75123. * @param name The name of the effect.
  75124. * @param direction The direction in which to blur the image.
  75125. * @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.
  75126. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75127. * @param camera The camera to apply the render pass to.
  75128. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75129. * @param engine The engine which the post process will be applied. (default: current engine)
  75130. * @param reusable If the post process can be reused on the same frame. (default: false)
  75131. * @param textureType Type of textures used when performing the post process. (default: 0)
  75132. * @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)
  75133. */
  75134. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75135. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75136. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75137. if (defines === void 0) { defines = ""; }
  75138. if (blockCompilation === void 0) { blockCompilation = false; }
  75139. 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;
  75140. _this.direction = direction;
  75141. _this.blockCompilation = blockCompilation;
  75142. _this._packedFloat = false;
  75143. _this._staticDefines = "";
  75144. _this._staticDefines = defines;
  75145. _this.onApplyObservable.add(function (effect) {
  75146. if (_this._outputTexture) {
  75147. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75148. }
  75149. else {
  75150. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75151. }
  75152. });
  75153. _this.kernel = kernel;
  75154. return _this;
  75155. }
  75156. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75157. /**
  75158. * Gets the length in pixels of the blur sample region
  75159. */
  75160. get: function () {
  75161. return this._idealKernel;
  75162. },
  75163. /**
  75164. * Sets the length in pixels of the blur sample region
  75165. */
  75166. set: function (v) {
  75167. if (this._idealKernel === v) {
  75168. return;
  75169. }
  75170. v = Math.max(v, 1);
  75171. this._idealKernel = v;
  75172. this._kernel = this._nearestBestKernel(v);
  75173. if (!this.blockCompilation) {
  75174. this._updateParameters();
  75175. }
  75176. },
  75177. enumerable: true,
  75178. configurable: true
  75179. });
  75180. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75181. /**
  75182. * Gets wether or not the blur is unpacking/repacking floats
  75183. */
  75184. get: function () {
  75185. return this._packedFloat;
  75186. },
  75187. /**
  75188. * Sets wether or not the blur needs to unpack/repack floats
  75189. */
  75190. set: function (v) {
  75191. if (this._packedFloat === v) {
  75192. return;
  75193. }
  75194. this._packedFloat = v;
  75195. if (!this.blockCompilation) {
  75196. this._updateParameters();
  75197. }
  75198. },
  75199. enumerable: true,
  75200. configurable: true
  75201. });
  75202. /**
  75203. * Updates the effect with the current post process compile time values and recompiles the shader.
  75204. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75205. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75206. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75207. * @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
  75208. * @param onCompiled Called when the shader has been compiled.
  75209. * @param onError Called if there is an error when compiling a shader.
  75210. */
  75211. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75212. if (defines === void 0) { defines = null; }
  75213. if (uniforms === void 0) { uniforms = null; }
  75214. if (samplers === void 0) { samplers = null; }
  75215. this._updateParameters(onCompiled, onError);
  75216. };
  75217. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75218. // Generate sampling offsets and weights
  75219. var N = this._kernel;
  75220. var centerIndex = (N - 1) / 2;
  75221. // Generate Gaussian sampling weights over kernel
  75222. var offsets = [];
  75223. var weights = [];
  75224. var totalWeight = 0;
  75225. for (var i = 0; i < N; i++) {
  75226. var u = i / (N - 1);
  75227. var w = this._gaussianWeight(u * 2.0 - 1);
  75228. offsets[i] = (i - centerIndex);
  75229. weights[i] = w;
  75230. totalWeight += w;
  75231. }
  75232. // Normalize weights
  75233. for (var i = 0; i < weights.length; i++) {
  75234. weights[i] /= totalWeight;
  75235. }
  75236. // Optimize: combine samples to take advantage of hardware linear sampling
  75237. // Walk from left to center, combining pairs (symmetrically)
  75238. var linearSamplingWeights = [];
  75239. var linearSamplingOffsets = [];
  75240. var linearSamplingMap = [];
  75241. for (var i = 0; i <= centerIndex; i += 2) {
  75242. var j = Math.min(i + 1, Math.floor(centerIndex));
  75243. var singleCenterSample = i === j;
  75244. if (singleCenterSample) {
  75245. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75246. }
  75247. else {
  75248. var sharedCell = j === centerIndex;
  75249. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75250. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75251. if (offsetLinear === 0) {
  75252. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75253. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75254. }
  75255. else {
  75256. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75257. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75258. }
  75259. }
  75260. }
  75261. for (var i = 0; i < linearSamplingMap.length; i++) {
  75262. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75263. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75264. }
  75265. // Replace with optimized
  75266. offsets = linearSamplingOffsets;
  75267. weights = linearSamplingWeights;
  75268. // Generate shaders
  75269. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75270. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75271. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75272. var defines = "";
  75273. defines += this._staticDefines;
  75274. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75275. if (this._staticDefines.indexOf("DOF") != -1) {
  75276. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75277. varyingCount--;
  75278. }
  75279. for (var i = 0; i < varyingCount; i++) {
  75280. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75281. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75282. }
  75283. var depCount = 0;
  75284. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75285. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75286. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75287. depCount++;
  75288. }
  75289. if (this.packedFloat) {
  75290. defines += "#define PACKEDFLOAT 1";
  75291. }
  75292. this.blockCompilation = false;
  75293. _super.prototype.updateEffect.call(this, defines, null, null, {
  75294. varyingCount: varyingCount,
  75295. depCount: depCount
  75296. }, onCompiled, onError);
  75297. };
  75298. /**
  75299. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75300. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75301. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75302. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75303. * The gaps between physical kernels are compensated for in the weighting of the samples
  75304. * @param idealKernel Ideal blur kernel.
  75305. * @return Nearest best kernel.
  75306. */
  75307. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75308. var v = Math.round(idealKernel);
  75309. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75310. var k = _a[_i];
  75311. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75312. return Math.max(k, 3);
  75313. }
  75314. }
  75315. return Math.max(v, 3);
  75316. };
  75317. /**
  75318. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75319. * @param x The point on the Gaussian distribution to sample.
  75320. * @return the value of the Gaussian function at x.
  75321. */
  75322. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75323. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75324. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75325. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75326. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75327. // truncated at around 1.3% of peak strength.
  75328. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75329. var sigma = (1 / 3);
  75330. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75331. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75332. var weight = (1.0 / denominator) * Math.exp(exponent);
  75333. return weight;
  75334. };
  75335. /**
  75336. * Generates a string that can be used as a floating point number in GLSL.
  75337. * @param x Value to print.
  75338. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75339. * @return GLSL float string.
  75340. */
  75341. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75342. if (decimalFigures === void 0) { decimalFigures = 8; }
  75343. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75344. };
  75345. return BlurPostProcess;
  75346. }(BABYLON.PostProcess));
  75347. BABYLON.BlurPostProcess = BlurPostProcess;
  75348. })(BABYLON || (BABYLON = {}));
  75349. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75350. var BABYLON;
  75351. (function (BABYLON) {
  75352. /**
  75353. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75354. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75355. * based on samples that have a large difference in distance than the center pixel.
  75356. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75357. */
  75358. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75359. __extends(DepthOfFieldBlurPostProcess, _super);
  75360. /**
  75361. * Creates a new instance CircleOfConfusionPostProcess
  75362. * @param name The name of the effect.
  75363. * @param scene The scene the effect belongs to.
  75364. * @param direction The direction the blur should be applied.
  75365. * @param kernel The size of the kernel used to blur.
  75366. * @param options The required width/height ratio to downsize to before computing the render pass.
  75367. * @param camera The camera to apply the render pass to.
  75368. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75369. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75370. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75371. * @param engine The engine which the post process will be applied. (default: current engine)
  75372. * @param reusable If the post process can be reused on the same frame. (default: false)
  75373. * @param textureType Type of textures used when performing the post process. (default: 0)
  75374. * @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)
  75375. */
  75376. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75377. if (imageToBlur === void 0) { imageToBlur = null; }
  75378. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75379. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75380. if (blockCompilation === void 0) { blockCompilation = false; }
  75381. 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;
  75382. _this.direction = direction;
  75383. _this.onApplyObservable.add(function (effect) {
  75384. if (imageToBlur != null) {
  75385. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75386. }
  75387. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75388. if (scene.activeCamera) {
  75389. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75390. }
  75391. });
  75392. return _this;
  75393. }
  75394. return DepthOfFieldBlurPostProcess;
  75395. }(BABYLON.BlurPostProcess));
  75396. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75397. })(BABYLON || (BABYLON = {}));
  75398. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75399. var BABYLON;
  75400. (function (BABYLON) {
  75401. /**
  75402. * Options to be set when merging outputs from the default pipeline.
  75403. */
  75404. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75405. function DepthOfFieldMergePostProcessOptions() {
  75406. }
  75407. return DepthOfFieldMergePostProcessOptions;
  75408. }());
  75409. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75410. /**
  75411. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75412. */
  75413. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75414. __extends(DepthOfFieldMergePostProcess, _super);
  75415. /**
  75416. * Creates a new instance of DepthOfFieldMergePostProcess
  75417. * @param name The name of the effect.
  75418. * @param originalFromInput Post process which's input will be used for the merge.
  75419. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75420. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75421. * @param options The required width/height ratio to downsize to before computing the render pass.
  75422. * @param camera The camera to apply the render pass to.
  75423. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75424. * @param engine The engine which the post process will be applied. (default: current engine)
  75425. * @param reusable If the post process can be reused on the same frame. (default: false)
  75426. * @param textureType Type of textures used when performing the post process. (default: 0)
  75427. * @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)
  75428. */
  75429. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75430. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75431. if (blockCompilation === void 0) { blockCompilation = false; }
  75432. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75433. _this.blurSteps = blurSteps;
  75434. _this.onApplyObservable.add(function (effect) {
  75435. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75436. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75437. blurSteps.forEach(function (step, index) {
  75438. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75439. });
  75440. });
  75441. if (!blockCompilation) {
  75442. _this.updateEffect();
  75443. }
  75444. return _this;
  75445. }
  75446. /**
  75447. * Updates the effect with the current post process compile time values and recompiles the shader.
  75448. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75449. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75450. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75451. * @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
  75452. * @param onCompiled Called when the shader has been compiled.
  75453. * @param onError Called if there is an error when compiling a shader.
  75454. */
  75455. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75456. if (defines === void 0) { defines = null; }
  75457. if (uniforms === void 0) { uniforms = null; }
  75458. if (samplers === void 0) { samplers = null; }
  75459. if (!defines) {
  75460. defines = "";
  75461. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75462. }
  75463. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75464. };
  75465. return DepthOfFieldMergePostProcess;
  75466. }(BABYLON.PostProcess));
  75467. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75468. })(BABYLON || (BABYLON = {}));
  75469. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75470. var BABYLON;
  75471. (function (BABYLON) {
  75472. /**
  75473. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75474. */
  75475. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75476. __extends(CircleOfConfusionPostProcess, _super);
  75477. /**
  75478. * Creates a new instance CircleOfConfusionPostProcess
  75479. * @param name The name of the effect.
  75480. * @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.
  75481. * @param options The required width/height ratio to downsize to before computing the render pass.
  75482. * @param camera The camera to apply the render pass to.
  75483. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75484. * @param engine The engine which the post process will be applied. (default: current engine)
  75485. * @param reusable If the post process can be reused on the same frame. (default: false)
  75486. * @param textureType Type of textures used when performing the post process. (default: 0)
  75487. * @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)
  75488. */
  75489. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75490. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75491. if (blockCompilation === void 0) { blockCompilation = false; }
  75492. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75493. /**
  75494. * 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.
  75495. */
  75496. _this.lensSize = 50;
  75497. /**
  75498. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75499. */
  75500. _this.fStop = 1.4;
  75501. /**
  75502. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75503. */
  75504. _this.focusDistance = 2000;
  75505. /**
  75506. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75507. */
  75508. _this.focalLength = 50;
  75509. _this._depthTexture = null;
  75510. _this._depthTexture = depthTexture;
  75511. _this.onApplyObservable.add(function (effect) {
  75512. if (!_this._depthTexture) {
  75513. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75514. return;
  75515. }
  75516. effect.setTexture("depthSampler", _this._depthTexture);
  75517. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75518. var aperture = _this.lensSize / _this.fStop;
  75519. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75520. effect.setFloat('focusDistance', _this.focusDistance);
  75521. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75522. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75523. });
  75524. return _this;
  75525. }
  75526. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75527. /**
  75528. * 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.
  75529. */
  75530. set: function (value) {
  75531. this._depthTexture = value;
  75532. },
  75533. enumerable: true,
  75534. configurable: true
  75535. });
  75536. return CircleOfConfusionPostProcess;
  75537. }(BABYLON.PostProcess));
  75538. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75539. })(BABYLON || (BABYLON = {}));
  75540. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75541. var BABYLON;
  75542. (function (BABYLON) {
  75543. /**
  75544. * Specifies the level of max blur that should be applied when using the depth of field effect
  75545. */
  75546. var DepthOfFieldEffectBlurLevel;
  75547. (function (DepthOfFieldEffectBlurLevel) {
  75548. /**
  75549. * Subtle blur
  75550. */
  75551. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75552. /**
  75553. * Medium blur
  75554. */
  75555. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75556. /**
  75557. * Large blur
  75558. */
  75559. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75560. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75561. ;
  75562. /**
  75563. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75564. */
  75565. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75566. __extends(DepthOfFieldEffect, _super);
  75567. /**
  75568. * Creates a new instance DepthOfFieldEffect
  75569. * @param scene The scene the effect belongs to.
  75570. * @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.
  75571. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75572. * @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)
  75573. */
  75574. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75575. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75576. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75577. if (blockCompilation === void 0) { blockCompilation = false; }
  75578. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75579. return _this._effects;
  75580. }, true) || this;
  75581. /**
  75582. * Internal post processes in depth of field effect
  75583. */
  75584. _this._effects = [];
  75585. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75586. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75587. // 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)
  75588. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75589. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75590. _this._depthOfFieldBlurY = [];
  75591. _this._depthOfFieldBlurX = [];
  75592. var blurCount = 1;
  75593. var kernelSize = 15;
  75594. switch (blurLevel) {
  75595. case DepthOfFieldEffectBlurLevel.High: {
  75596. blurCount = 3;
  75597. kernelSize = 51;
  75598. break;
  75599. }
  75600. case DepthOfFieldEffectBlurLevel.Medium: {
  75601. blurCount = 2;
  75602. kernelSize = 31;
  75603. break;
  75604. }
  75605. default: {
  75606. kernelSize = 15;
  75607. blurCount = 1;
  75608. break;
  75609. }
  75610. }
  75611. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75612. var ratio = 1.0;
  75613. for (var i = 0; i < blurCount; i++) {
  75614. 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);
  75615. blurY.autoClear = false;
  75616. ratio = 0.75 / Math.pow(2, i);
  75617. 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);
  75618. blurX.autoClear = false;
  75619. _this._depthOfFieldBlurY.push(blurY);
  75620. _this._depthOfFieldBlurX.push(blurX);
  75621. }
  75622. // Set all post processes on the effect.
  75623. _this._effects = [_this._circleOfConfusion];
  75624. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75625. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75626. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75627. }
  75628. // Merge blurred images with original image based on circleOfConfusion
  75629. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75630. _this._dofMerge.autoClear = false;
  75631. _this._effects.push(_this._dofMerge);
  75632. return _this;
  75633. }
  75634. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75635. get: function () {
  75636. return this._circleOfConfusion.focalLength;
  75637. },
  75638. /**
  75639. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75640. */
  75641. set: function (value) {
  75642. this._circleOfConfusion.focalLength = value;
  75643. },
  75644. enumerable: true,
  75645. configurable: true
  75646. });
  75647. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75648. get: function () {
  75649. return this._circleOfConfusion.fStop;
  75650. },
  75651. /**
  75652. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75653. */
  75654. set: function (value) {
  75655. this._circleOfConfusion.fStop = value;
  75656. },
  75657. enumerable: true,
  75658. configurable: true
  75659. });
  75660. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75661. get: function () {
  75662. return this._circleOfConfusion.focusDistance;
  75663. },
  75664. /**
  75665. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75666. */
  75667. set: function (value) {
  75668. this._circleOfConfusion.focusDistance = value;
  75669. },
  75670. enumerable: true,
  75671. configurable: true
  75672. });
  75673. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75674. get: function () {
  75675. return this._circleOfConfusion.lensSize;
  75676. },
  75677. /**
  75678. * 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.
  75679. */
  75680. set: function (value) {
  75681. this._circleOfConfusion.lensSize = value;
  75682. },
  75683. enumerable: true,
  75684. configurable: true
  75685. });
  75686. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75687. /**
  75688. * 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.
  75689. */
  75690. set: function (value) {
  75691. this._circleOfConfusion.depthTexture = value;
  75692. },
  75693. enumerable: true,
  75694. configurable: true
  75695. });
  75696. /**
  75697. * Disposes each of the internal effects for a given camera.
  75698. * @param camera The camera to dispose the effect on.
  75699. */
  75700. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75701. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75702. this._effects[effectIndex].dispose(camera);
  75703. }
  75704. };
  75705. /**
  75706. * Internal
  75707. */
  75708. DepthOfFieldEffect.prototype._updateEffects = function () {
  75709. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75710. this._effects[effectIndex].updateEffect();
  75711. }
  75712. };
  75713. /**
  75714. * Internal
  75715. * @returns if all the contained post processes are ready.
  75716. */
  75717. DepthOfFieldEffect.prototype._isReady = function () {
  75718. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75719. if (!this._effects[effectIndex].isReady()) {
  75720. return false;
  75721. }
  75722. }
  75723. return true;
  75724. };
  75725. return DepthOfFieldEffect;
  75726. }(BABYLON.PostProcessRenderEffect));
  75727. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75728. })(BABYLON || (BABYLON = {}));
  75729. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75730. var BABYLON;
  75731. (function (BABYLON) {
  75732. /**
  75733. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75734. */
  75735. var BloomMergePostProcess = /** @class */ (function (_super) {
  75736. __extends(BloomMergePostProcess, _super);
  75737. /**
  75738. * Creates a new instance of @see BloomMergePostProcess
  75739. * @param name The name of the effect.
  75740. * @param originalFromInput Post process which's input will be used for the merge.
  75741. * @param blurred Blurred highlights post process which's output will be used.
  75742. * @param weight Weight of the bloom to be added to the original input.
  75743. * @param options The required width/height ratio to downsize to before computing the render pass.
  75744. * @param camera The camera to apply the render pass to.
  75745. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75746. * @param engine The engine which the post process will be applied. (default: current engine)
  75747. * @param reusable If the post process can be reused on the same frame. (default: false)
  75748. * @param textureType Type of textures used when performing the post process. (default: 0)
  75749. * @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)
  75750. */
  75751. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75752. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75753. if (blockCompilation === void 0) { blockCompilation = false; }
  75754. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75755. _this.weight = weight;
  75756. _this.onApplyObservable.add(function (effect) {
  75757. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75758. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75759. effect.setFloat("bloomWeight", _this.weight);
  75760. });
  75761. if (!blockCompilation) {
  75762. _this.updateEffect();
  75763. }
  75764. return _this;
  75765. }
  75766. return BloomMergePostProcess;
  75767. }(BABYLON.PostProcess));
  75768. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75769. })(BABYLON || (BABYLON = {}));
  75770. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75771. var BABYLON;
  75772. (function (BABYLON) {
  75773. /**
  75774. * 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.
  75775. */
  75776. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75777. __extends(ExtractHighlightsPostProcess, _super);
  75778. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75779. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75780. if (blockCompilation === void 0) { blockCompilation = false; }
  75781. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75782. /**
  75783. * The luminance threshold, pixels below this value will be set to black.
  75784. */
  75785. _this.threshold = 0.9;
  75786. /**
  75787. * Internal
  75788. */
  75789. _this._exposure = 1;
  75790. /**
  75791. * Post process which has the input texture to be used when performing highlight extraction
  75792. */
  75793. _this._inputPostProcess = null;
  75794. _this.onApplyObservable.add(function (effect) {
  75795. if (_this._inputPostProcess) {
  75796. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75797. }
  75798. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75799. effect.setFloat('exposure', _this._exposure);
  75800. });
  75801. return _this;
  75802. }
  75803. return ExtractHighlightsPostProcess;
  75804. }(BABYLON.PostProcess));
  75805. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75806. })(BABYLON || (BABYLON = {}));
  75807. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75808. var BABYLON;
  75809. (function (BABYLON) {
  75810. /**
  75811. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75812. */
  75813. var BloomEffect = /** @class */ (function (_super) {
  75814. __extends(BloomEffect, _super);
  75815. /**
  75816. * Creates a new instance of @see BloomEffect
  75817. * @param scene The scene the effect belongs to.
  75818. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75819. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75820. * @param bloomWeight The the strength of bloom.
  75821. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75822. * @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)
  75823. */
  75824. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75825. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75826. if (blockCompilation === void 0) { blockCompilation = false; }
  75827. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75828. return _this._effects;
  75829. }, true) || this;
  75830. _this.bloomScale = bloomScale;
  75831. /**
  75832. * Internal
  75833. */
  75834. _this._effects = [];
  75835. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75836. _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);
  75837. _this._blurX.alwaysForcePOT = true;
  75838. _this._blurX.autoClear = false;
  75839. _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);
  75840. _this._blurY.alwaysForcePOT = true;
  75841. _this._blurY.autoClear = false;
  75842. _this.kernel = bloomKernel;
  75843. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75844. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75845. _this._merge.autoClear = false;
  75846. _this._effects.push(_this._merge);
  75847. return _this;
  75848. }
  75849. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75850. /**
  75851. * The luminance threshold to find bright areas of the image to bloom.
  75852. */
  75853. get: function () {
  75854. return this._downscale.threshold;
  75855. },
  75856. set: function (value) {
  75857. this._downscale.threshold = value;
  75858. },
  75859. enumerable: true,
  75860. configurable: true
  75861. });
  75862. Object.defineProperty(BloomEffect.prototype, "weight", {
  75863. /**
  75864. * The strength of the bloom.
  75865. */
  75866. get: function () {
  75867. return this._merge.weight;
  75868. },
  75869. set: function (value) {
  75870. this._merge.weight = value;
  75871. },
  75872. enumerable: true,
  75873. configurable: true
  75874. });
  75875. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75876. /**
  75877. * Specifies the size of the bloom blur kernel, relative to the final output size
  75878. */
  75879. get: function () {
  75880. return this._blurX.kernel / this.bloomScale;
  75881. },
  75882. set: function (value) {
  75883. this._blurX.kernel = value * this.bloomScale;
  75884. this._blurY.kernel = value * this.bloomScale;
  75885. },
  75886. enumerable: true,
  75887. configurable: true
  75888. });
  75889. /**
  75890. * Disposes each of the internal effects for a given camera.
  75891. * @param camera The camera to dispose the effect on.
  75892. */
  75893. BloomEffect.prototype.disposeEffects = function (camera) {
  75894. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75895. this._effects[effectIndex].dispose(camera);
  75896. }
  75897. };
  75898. /**
  75899. * Internal
  75900. */
  75901. BloomEffect.prototype._updateEffects = function () {
  75902. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75903. this._effects[effectIndex].updateEffect();
  75904. }
  75905. };
  75906. /**
  75907. * Internal
  75908. * @returns if all the contained post processes are ready.
  75909. */
  75910. BloomEffect.prototype._isReady = function () {
  75911. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75912. if (!this._effects[effectIndex].isReady()) {
  75913. return false;
  75914. }
  75915. }
  75916. return true;
  75917. };
  75918. return BloomEffect;
  75919. }(BABYLON.PostProcessRenderEffect));
  75920. BABYLON.BloomEffect = BloomEffect;
  75921. })(BABYLON || (BABYLON = {}));
  75922. //# sourceMappingURL=babylon.bloomEffect.js.map
  75923. var BABYLON;
  75924. (function (BABYLON) {
  75925. /**
  75926. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75927. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75928. */
  75929. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75930. __extends(DefaultRenderingPipeline, _super);
  75931. /**
  75932. * @constructor
  75933. * @param {string} name - The rendering pipeline name (default: "")
  75934. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75935. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75936. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75937. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75938. */
  75939. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75940. if (name === void 0) { name = ""; }
  75941. if (hdr === void 0) { hdr = true; }
  75942. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75943. if (automaticBuild === void 0) { automaticBuild = true; }
  75944. var _this = _super.call(this, scene.getEngine(), name) || this;
  75945. _this._originalCameras = [];
  75946. /**
  75947. * ID of the sharpen post process,
  75948. */
  75949. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75950. /**
  75951. * ID of the image processing post process;
  75952. */
  75953. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75954. /**
  75955. * ID of the Fast Approximate Anti-Aliasing post process;
  75956. */
  75957. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75958. /**
  75959. * ID of the chromatic aberration post process,
  75960. */
  75961. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75962. /**
  75963. * ID of the grain post process
  75964. */
  75965. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75966. /**
  75967. * Glow post process which adds a glow to emmisive areas of the image
  75968. */
  75969. _this._glowLayer = null;
  75970. /**
  75971. * Animations which can be used to tweak settings over a period of time
  75972. */
  75973. _this.animations = [];
  75974. _this._imageProcessingConfigurationObserver = null;
  75975. // Values
  75976. _this._sharpenEnabled = false;
  75977. _this._bloomEnabled = false;
  75978. _this._depthOfFieldEnabled = false;
  75979. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75980. _this._fxaaEnabled = false;
  75981. _this._imageProcessingEnabled = true;
  75982. _this._bloomScale = 0.5;
  75983. _this._chromaticAberrationEnabled = false;
  75984. _this._grainEnabled = false;
  75985. _this._buildAllowed = true;
  75986. _this._resizeObserver = null;
  75987. _this._hardwareScaleLevel = 1.0;
  75988. _this._bloomKernel = 64;
  75989. /**
  75990. * Specifies the weight of the bloom in the final rendering
  75991. */
  75992. _this._bloomWeight = 0.15;
  75993. /**
  75994. * Specifies the luma threshold for the area that will be blurred by the bloom
  75995. */
  75996. _this._bloomThreshold = 0.9;
  75997. _this._samples = 1;
  75998. _this._hasCleared = false;
  75999. _this._prevPostProcess = null;
  76000. _this._prevPrevPostProcess = null;
  76001. _this._cameras = cameras || scene.cameras;
  76002. _this._originalCameras = _this._cameras.slice();
  76003. _this._buildAllowed = automaticBuild;
  76004. // Initialize
  76005. _this._scene = scene;
  76006. var caps = _this._scene.getEngine().getCaps();
  76007. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76008. // Misc
  76009. if (_this._hdr) {
  76010. if (caps.textureHalfFloatRender) {
  76011. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76012. }
  76013. else if (caps.textureFloatRender) {
  76014. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76015. }
  76016. }
  76017. else {
  76018. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76019. }
  76020. // Attach
  76021. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76022. var engine = _this._scene.getEngine();
  76023. // Create post processes before hand so they can be modified before enabled.
  76024. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76025. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76026. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76027. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76028. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76029. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76030. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76031. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76032. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76033. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76034. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76035. _this.bloomKernel = _this.bloomKernel;
  76036. });
  76037. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76038. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76039. });
  76040. _this._buildPipeline();
  76041. return _this;
  76042. }
  76043. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76044. get: function () {
  76045. return this._sharpenEnabled;
  76046. },
  76047. /**
  76048. * Enable or disable the sharpen process from the pipeline
  76049. */
  76050. set: function (enabled) {
  76051. if (this._sharpenEnabled === enabled) {
  76052. return;
  76053. }
  76054. this._sharpenEnabled = enabled;
  76055. this._buildPipeline();
  76056. },
  76057. enumerable: true,
  76058. configurable: true
  76059. });
  76060. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76061. /**
  76062. * Specifies the size of the bloom blur kernel, relative to the final output size
  76063. */
  76064. get: function () {
  76065. return this._bloomKernel;
  76066. },
  76067. set: function (value) {
  76068. this._bloomKernel = value;
  76069. this.bloom.kernel = value / this._hardwareScaleLevel;
  76070. },
  76071. enumerable: true,
  76072. configurable: true
  76073. });
  76074. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76075. get: function () {
  76076. return this._bloomWeight;
  76077. },
  76078. /**
  76079. * The strength of the bloom.
  76080. */
  76081. set: function (value) {
  76082. if (this._bloomWeight === value) {
  76083. return;
  76084. }
  76085. this.bloom.weight = value;
  76086. this._bloomWeight = value;
  76087. },
  76088. enumerable: true,
  76089. configurable: true
  76090. });
  76091. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76092. get: function () {
  76093. return this._bloomThreshold;
  76094. },
  76095. /**
  76096. * The strength of the bloom.
  76097. */
  76098. set: function (value) {
  76099. if (this._bloomThreshold === value) {
  76100. return;
  76101. }
  76102. this.bloom.threshold = value;
  76103. this._bloomThreshold = value;
  76104. },
  76105. enumerable: true,
  76106. configurable: true
  76107. });
  76108. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76109. get: function () {
  76110. return this._bloomScale;
  76111. },
  76112. /**
  76113. * The scale of the bloom, lower value will provide better performance.
  76114. */
  76115. set: function (value) {
  76116. if (this._bloomScale === value) {
  76117. return;
  76118. }
  76119. this._bloomScale = value;
  76120. // recreate bloom and dispose old as this setting is not dynamic
  76121. this._rebuildBloom();
  76122. this._buildPipeline();
  76123. },
  76124. enumerable: true,
  76125. configurable: true
  76126. });
  76127. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76128. get: function () {
  76129. return this._bloomEnabled;
  76130. },
  76131. /**
  76132. * Enable or disable the bloom from the pipeline
  76133. */
  76134. set: function (enabled) {
  76135. if (this._bloomEnabled === enabled) {
  76136. return;
  76137. }
  76138. this._bloomEnabled = enabled;
  76139. this._buildPipeline();
  76140. },
  76141. enumerable: true,
  76142. configurable: true
  76143. });
  76144. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76145. // recreate bloom and dispose old as this setting is not dynamic
  76146. var oldBloom = this.bloom;
  76147. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76148. this.bloom.threshold = oldBloom.threshold;
  76149. for (var i = 0; i < this._cameras.length; i++) {
  76150. oldBloom.disposeEffects(this._cameras[i]);
  76151. }
  76152. };
  76153. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76154. /**
  76155. * If the depth of field is enabled.
  76156. */
  76157. get: function () {
  76158. return this._depthOfFieldEnabled;
  76159. },
  76160. set: function (enabled) {
  76161. if (this._depthOfFieldEnabled === enabled) {
  76162. return;
  76163. }
  76164. this._depthOfFieldEnabled = enabled;
  76165. this._buildPipeline();
  76166. },
  76167. enumerable: true,
  76168. configurable: true
  76169. });
  76170. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76171. /**
  76172. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76173. */
  76174. get: function () {
  76175. return this._depthOfFieldBlurLevel;
  76176. },
  76177. set: function (value) {
  76178. if (this._depthOfFieldBlurLevel === value) {
  76179. return;
  76180. }
  76181. this._depthOfFieldBlurLevel = value;
  76182. // recreate dof and dispose old as this setting is not dynamic
  76183. var oldDof = this.depthOfField;
  76184. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76185. this.depthOfField.focalLength = oldDof.focalLength;
  76186. this.depthOfField.focusDistance = oldDof.focusDistance;
  76187. this.depthOfField.fStop = oldDof.fStop;
  76188. this.depthOfField.lensSize = oldDof.lensSize;
  76189. for (var i = 0; i < this._cameras.length; i++) {
  76190. oldDof.disposeEffects(this._cameras[i]);
  76191. }
  76192. this._buildPipeline();
  76193. },
  76194. enumerable: true,
  76195. configurable: true
  76196. });
  76197. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76198. get: function () {
  76199. return this._fxaaEnabled;
  76200. },
  76201. /**
  76202. * If the anti aliasing is enabled.
  76203. */
  76204. set: function (enabled) {
  76205. if (this._fxaaEnabled === enabled) {
  76206. return;
  76207. }
  76208. this._fxaaEnabled = enabled;
  76209. this._buildPipeline();
  76210. },
  76211. enumerable: true,
  76212. configurable: true
  76213. });
  76214. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76215. get: function () {
  76216. return this._samples;
  76217. },
  76218. /**
  76219. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76220. */
  76221. set: function (sampleCount) {
  76222. if (this._samples === sampleCount) {
  76223. return;
  76224. }
  76225. this._samples = sampleCount;
  76226. this._buildPipeline();
  76227. },
  76228. enumerable: true,
  76229. configurable: true
  76230. });
  76231. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76232. get: function () {
  76233. return this._imageProcessingEnabled;
  76234. },
  76235. /**
  76236. * If image processing is enabled.
  76237. */
  76238. set: function (enabled) {
  76239. if (this._imageProcessingEnabled === enabled) {
  76240. return;
  76241. }
  76242. this._imageProcessingEnabled = enabled;
  76243. this._buildPipeline();
  76244. },
  76245. enumerable: true,
  76246. configurable: true
  76247. });
  76248. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76249. get: function () {
  76250. return this._glowLayer == null;
  76251. },
  76252. /**
  76253. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76254. */
  76255. set: function (enabled) {
  76256. if (enabled && !this._glowLayer) {
  76257. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76258. }
  76259. else if (!enabled && this._glowLayer) {
  76260. this._glowLayer.dispose();
  76261. this._glowLayer = null;
  76262. }
  76263. },
  76264. enumerable: true,
  76265. configurable: true
  76266. });
  76267. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76268. get: function () {
  76269. return this._chromaticAberrationEnabled;
  76270. },
  76271. /**
  76272. * Enable or disable the chromaticAberration process from the pipeline
  76273. */
  76274. set: function (enabled) {
  76275. if (this._chromaticAberrationEnabled === enabled) {
  76276. return;
  76277. }
  76278. this._chromaticAberrationEnabled = enabled;
  76279. this._buildPipeline();
  76280. },
  76281. enumerable: true,
  76282. configurable: true
  76283. });
  76284. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76285. get: function () {
  76286. return this._grainEnabled;
  76287. },
  76288. /**
  76289. * Enable or disable the grain process from the pipeline
  76290. */
  76291. set: function (enabled) {
  76292. if (this._grainEnabled === enabled) {
  76293. return;
  76294. }
  76295. this._grainEnabled = enabled;
  76296. this._buildPipeline();
  76297. },
  76298. enumerable: true,
  76299. configurable: true
  76300. });
  76301. /**
  76302. * Force the compilation of the entire pipeline.
  76303. */
  76304. DefaultRenderingPipeline.prototype.prepare = function () {
  76305. var previousState = this._buildAllowed;
  76306. this._buildAllowed = true;
  76307. this._buildPipeline();
  76308. this._buildAllowed = previousState;
  76309. };
  76310. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76311. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76312. if (this._hasCleared) {
  76313. postProcess.autoClear = false;
  76314. }
  76315. else {
  76316. postProcess.autoClear = true;
  76317. this._scene.autoClear = false;
  76318. this._hasCleared = true;
  76319. }
  76320. if (!skipTextureSharing) {
  76321. if (this._prevPrevPostProcess) {
  76322. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76323. }
  76324. else {
  76325. postProcess.useOwnOutput();
  76326. }
  76327. if (this._prevPostProcess) {
  76328. this._prevPrevPostProcess = this._prevPostProcess;
  76329. }
  76330. this._prevPostProcess = postProcess;
  76331. }
  76332. };
  76333. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76334. var _this = this;
  76335. if (!this._buildAllowed) {
  76336. return;
  76337. }
  76338. this._scene.autoClear = true;
  76339. var engine = this._scene.getEngine();
  76340. this._disposePostProcesses();
  76341. if (this._cameras !== null) {
  76342. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76343. // get back cameras to be used to reattach pipeline
  76344. this._cameras = this._originalCameras.slice();
  76345. }
  76346. this._reset();
  76347. this._prevPostProcess = null;
  76348. this._prevPrevPostProcess = null;
  76349. this._hasCleared = false;
  76350. if (this.depthOfFieldEnabled) {
  76351. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76352. this.depthOfField.depthTexture = depthTexture;
  76353. if (!this.depthOfField._isReady()) {
  76354. this.depthOfField._updateEffects();
  76355. }
  76356. this.addEffect(this.depthOfField);
  76357. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76358. }
  76359. if (this.bloomEnabled) {
  76360. if (!this.bloom._isReady()) {
  76361. this.bloom._updateEffects();
  76362. }
  76363. this.addEffect(this.bloom);
  76364. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76365. }
  76366. if (this._imageProcessingEnabled) {
  76367. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76368. if (this._hdr) {
  76369. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76370. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76371. }
  76372. else {
  76373. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76374. }
  76375. }
  76376. if (this.sharpenEnabled) {
  76377. if (!this.sharpen.isReady()) {
  76378. this.sharpen.updateEffect();
  76379. }
  76380. this.addEffect(this._sharpenEffect);
  76381. this._setAutoClearAndTextureSharing(this.sharpen);
  76382. }
  76383. if (this.grainEnabled) {
  76384. if (!this.grain.isReady()) {
  76385. this.grain.updateEffect();
  76386. }
  76387. this.addEffect(this._grainEffect);
  76388. this._setAutoClearAndTextureSharing(this.grain);
  76389. }
  76390. if (this.chromaticAberrationEnabled) {
  76391. if (!this.chromaticAberration.isReady()) {
  76392. this.chromaticAberration.updateEffect();
  76393. }
  76394. this.addEffect(this._chromaticAberrationEffect);
  76395. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76396. }
  76397. if (this.fxaaEnabled) {
  76398. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76399. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76400. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76401. }
  76402. if (this._cameras !== null) {
  76403. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76404. }
  76405. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76406. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76407. }
  76408. };
  76409. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76410. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76411. for (var i = 0; i < this._cameras.length; i++) {
  76412. var camera = this._cameras[i];
  76413. if (this.imageProcessing) {
  76414. this.imageProcessing.dispose(camera);
  76415. }
  76416. if (this.fxaa) {
  76417. this.fxaa.dispose(camera);
  76418. }
  76419. // These are created in the constructor and should not be disposed on every pipeline change
  76420. if (disposeNonRecreated) {
  76421. if (this.sharpen) {
  76422. this.sharpen.dispose(camera);
  76423. }
  76424. if (this.depthOfField) {
  76425. this.depthOfField.disposeEffects(camera);
  76426. }
  76427. if (this.bloom) {
  76428. this.bloom.disposeEffects(camera);
  76429. }
  76430. if (this.chromaticAberration) {
  76431. this.chromaticAberration.dispose(camera);
  76432. }
  76433. if (this.grain) {
  76434. this.grain.dispose(camera);
  76435. }
  76436. if (this._glowLayer) {
  76437. this._glowLayer.dispose();
  76438. }
  76439. }
  76440. }
  76441. this.imageProcessing = null;
  76442. this.fxaa = null;
  76443. if (disposeNonRecreated) {
  76444. this.sharpen = null;
  76445. this._sharpenEffect = null;
  76446. this.depthOfField = null;
  76447. this.bloom = null;
  76448. this.chromaticAberration = null;
  76449. this._chromaticAberrationEffect = null;
  76450. this.grain = null;
  76451. this._grainEffect = null;
  76452. this._glowLayer = null;
  76453. }
  76454. };
  76455. /**
  76456. * Dispose of the pipeline and stop all post processes
  76457. */
  76458. DefaultRenderingPipeline.prototype.dispose = function () {
  76459. this._disposePostProcesses(true);
  76460. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76461. this._scene.autoClear = true;
  76462. if (this._resizeObserver) {
  76463. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76464. this._resizeObserver = null;
  76465. }
  76466. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76467. _super.prototype.dispose.call(this);
  76468. };
  76469. /**
  76470. * Serialize the rendering pipeline (Used when exporting)
  76471. * @returns the serialized object
  76472. */
  76473. DefaultRenderingPipeline.prototype.serialize = function () {
  76474. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76475. serializationObject.customType = "DefaultRenderingPipeline";
  76476. return serializationObject;
  76477. };
  76478. /**
  76479. * Parse the serialized pipeline
  76480. * @param source Source pipeline.
  76481. * @param scene The scene to load the pipeline to.
  76482. * @param rootUrl The URL of the serialized pipeline.
  76483. * @returns An instantiated pipeline from the serialized object.
  76484. */
  76485. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76486. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76487. };
  76488. __decorate([
  76489. BABYLON.serialize()
  76490. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76491. __decorate([
  76492. BABYLON.serialize()
  76493. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76494. __decorate([
  76495. BABYLON.serialize()
  76496. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76497. __decorate([
  76498. BABYLON.serialize()
  76499. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76500. __decorate([
  76501. BABYLON.serialize()
  76502. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76503. __decorate([
  76504. BABYLON.serialize()
  76505. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76506. __decorate([
  76507. BABYLON.serialize()
  76508. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76509. __decorate([
  76510. BABYLON.serialize()
  76511. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76512. __decorate([
  76513. BABYLON.serialize()
  76514. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76515. __decorate([
  76516. BABYLON.serialize()
  76517. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76518. __decorate([
  76519. BABYLON.serialize()
  76520. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76521. __decorate([
  76522. BABYLON.serialize()
  76523. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76524. __decorate([
  76525. BABYLON.serialize()
  76526. ], DefaultRenderingPipeline.prototype, "samples", null);
  76527. __decorate([
  76528. BABYLON.serialize()
  76529. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76530. __decorate([
  76531. BABYLON.serialize()
  76532. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76533. __decorate([
  76534. BABYLON.serialize()
  76535. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76536. __decorate([
  76537. BABYLON.serialize()
  76538. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76539. return DefaultRenderingPipeline;
  76540. }(BABYLON.PostProcessRenderPipeline));
  76541. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76542. })(BABYLON || (BABYLON = {}));
  76543. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76544. var BABYLON;
  76545. (function (BABYLON) {
  76546. /**
  76547. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76548. */
  76549. var GeometryBufferRenderer = /** @class */ (function () {
  76550. /**
  76551. * Creates a new G Buffer for the scene
  76552. * @param scene The scene the buffer belongs to
  76553. * @param ratio How big is the buffer related to the main canvas.
  76554. */
  76555. function GeometryBufferRenderer(scene, ratio) {
  76556. if (ratio === void 0) { ratio = 1; }
  76557. this._enablePosition = false;
  76558. this._scene = scene;
  76559. this._ratio = ratio;
  76560. // Render target
  76561. this._createRenderTargets();
  76562. }
  76563. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76564. /**
  76565. * Set the render list (meshes to be rendered) used in the G buffer.
  76566. */
  76567. set: function (meshes) {
  76568. this._multiRenderTarget.renderList = meshes;
  76569. },
  76570. enumerable: true,
  76571. configurable: true
  76572. });
  76573. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76574. /**
  76575. * Gets wether or not G buffer are supported by the running hardware.
  76576. * This requires draw buffer supports
  76577. */
  76578. get: function () {
  76579. return this._multiRenderTarget.isSupported;
  76580. },
  76581. enumerable: true,
  76582. configurable: true
  76583. });
  76584. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76585. /**
  76586. * Gets wether or not position are enabled for the G buffer.
  76587. */
  76588. get: function () {
  76589. return this._enablePosition;
  76590. },
  76591. /**
  76592. * Sets wether or not position are enabled for the G buffer.
  76593. */
  76594. set: function (enable) {
  76595. this._enablePosition = enable;
  76596. this.dispose();
  76597. this._createRenderTargets();
  76598. },
  76599. enumerable: true,
  76600. configurable: true
  76601. });
  76602. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76603. /**
  76604. * Gets the scene associated with the buffer.
  76605. */
  76606. get: function () {
  76607. return this._scene;
  76608. },
  76609. enumerable: true,
  76610. configurable: true
  76611. });
  76612. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76613. /**
  76614. * Gets the ratio used by the buffer during its creation.
  76615. * How big is the buffer related to the main canvas.
  76616. */
  76617. get: function () {
  76618. return this._ratio;
  76619. },
  76620. enumerable: true,
  76621. configurable: true
  76622. });
  76623. /**
  76624. * Checks wether everything is ready to render a submesh to the G buffer.
  76625. * @param subMesh the submesh to check readiness for
  76626. * @param useInstances is the mesh drawn using instance or not
  76627. * @returns true if ready otherwise false
  76628. */
  76629. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76630. var material = subMesh.getMaterial();
  76631. if (material && material.disableDepthWrite) {
  76632. return false;
  76633. }
  76634. var defines = [];
  76635. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76636. var mesh = subMesh.getMesh();
  76637. // Alpha test
  76638. if (material && material.needAlphaTesting()) {
  76639. defines.push("#define ALPHATEST");
  76640. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76641. attribs.push(BABYLON.VertexBuffer.UVKind);
  76642. defines.push("#define UV1");
  76643. }
  76644. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76645. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76646. defines.push("#define UV2");
  76647. }
  76648. }
  76649. // Buffers
  76650. if (this._enablePosition) {
  76651. defines.push("#define POSITION");
  76652. }
  76653. // Bones
  76654. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76655. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76656. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76657. if (mesh.numBoneInfluencers > 4) {
  76658. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76659. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76660. }
  76661. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76662. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76663. }
  76664. else {
  76665. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76666. }
  76667. // Instances
  76668. if (useInstances) {
  76669. defines.push("#define INSTANCES");
  76670. attribs.push("world0");
  76671. attribs.push("world1");
  76672. attribs.push("world2");
  76673. attribs.push("world3");
  76674. }
  76675. // Get correct effect
  76676. var join = defines.join("\n");
  76677. if (this._cachedDefines !== join) {
  76678. this._cachedDefines = join;
  76679. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76680. }
  76681. return this._effect.isReady();
  76682. };
  76683. /**
  76684. * Gets the current underlying G Buffer.
  76685. * @returns the buffer
  76686. */
  76687. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76688. return this._multiRenderTarget;
  76689. };
  76690. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76691. /**
  76692. * Gets the number of samples used to render the buffer (anti aliasing).
  76693. */
  76694. get: function () {
  76695. return this._multiRenderTarget.samples;
  76696. },
  76697. /**
  76698. * Sets the number of samples used to render the buffer (anti aliasing).
  76699. */
  76700. set: function (value) {
  76701. this._multiRenderTarget.samples = value;
  76702. },
  76703. enumerable: true,
  76704. configurable: true
  76705. });
  76706. /**
  76707. * Disposes the renderer and frees up associated resources.
  76708. */
  76709. GeometryBufferRenderer.prototype.dispose = function () {
  76710. this.getGBuffer().dispose();
  76711. };
  76712. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76713. var _this = this;
  76714. var engine = this._scene.getEngine();
  76715. var count = this._enablePosition ? 3 : 2;
  76716. 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 });
  76717. if (!this.isSupported) {
  76718. return;
  76719. }
  76720. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76721. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76722. this._multiRenderTarget.refreshRate = 1;
  76723. this._multiRenderTarget.renderParticles = false;
  76724. this._multiRenderTarget.renderList = null;
  76725. // set default depth value to 1.0 (far away)
  76726. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76727. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76728. });
  76729. // Custom render function
  76730. var renderSubMesh = function (subMesh) {
  76731. var mesh = subMesh.getRenderingMesh();
  76732. var scene = _this._scene;
  76733. var engine = scene.getEngine();
  76734. var material = subMesh.getMaterial();
  76735. if (!material) {
  76736. return;
  76737. }
  76738. // Culling
  76739. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76740. // Managing instances
  76741. var batch = mesh._getInstancesRenderList(subMesh._id);
  76742. if (batch.mustReturn) {
  76743. return;
  76744. }
  76745. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76746. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76747. engine.enableEffect(_this._effect);
  76748. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76749. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76750. _this._effect.setMatrix("view", scene.getViewMatrix());
  76751. // Alpha test
  76752. if (material && material.needAlphaTesting()) {
  76753. var alphaTexture = material.getAlphaTestTexture();
  76754. if (alphaTexture) {
  76755. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76756. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76757. }
  76758. }
  76759. // Bones
  76760. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76761. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76762. }
  76763. // Draw
  76764. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76765. }
  76766. };
  76767. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76768. var index;
  76769. if (depthOnlySubMeshes.length) {
  76770. engine.setColorWrite(false);
  76771. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76772. renderSubMesh(depthOnlySubMeshes.data[index]);
  76773. }
  76774. engine.setColorWrite(true);
  76775. }
  76776. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76777. renderSubMesh(opaqueSubMeshes.data[index]);
  76778. }
  76779. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76780. renderSubMesh(alphaTestSubMeshes.data[index]);
  76781. }
  76782. };
  76783. };
  76784. return GeometryBufferRenderer;
  76785. }());
  76786. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76787. })(BABYLON || (BABYLON = {}));
  76788. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76789. var BABYLON;
  76790. (function (BABYLON) {
  76791. var RefractionPostProcess = /** @class */ (function (_super) {
  76792. __extends(RefractionPostProcess, _super);
  76793. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76794. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76795. _this.color = color;
  76796. _this.depth = depth;
  76797. _this.colorLevel = colorLevel;
  76798. _this._ownRefractionTexture = true;
  76799. _this.onActivateObservable.add(function (cam) {
  76800. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76801. });
  76802. _this.onApplyObservable.add(function (effect) {
  76803. effect.setColor3("baseColor", _this.color);
  76804. effect.setFloat("depth", _this.depth);
  76805. effect.setFloat("colorLevel", _this.colorLevel);
  76806. effect.setTexture("refractionSampler", _this._refTexture);
  76807. });
  76808. return _this;
  76809. }
  76810. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76811. /**
  76812. * Gets or sets the refraction texture
  76813. * Please note that you are responsible for disposing the texture if you set it manually
  76814. */
  76815. get: function () {
  76816. return this._refTexture;
  76817. },
  76818. set: function (value) {
  76819. if (this._refTexture && this._ownRefractionTexture) {
  76820. this._refTexture.dispose();
  76821. }
  76822. this._refTexture = value;
  76823. this._ownRefractionTexture = false;
  76824. },
  76825. enumerable: true,
  76826. configurable: true
  76827. });
  76828. // Methods
  76829. RefractionPostProcess.prototype.dispose = function (camera) {
  76830. if (this._refTexture && this._ownRefractionTexture) {
  76831. this._refTexture.dispose();
  76832. this._refTexture = null;
  76833. }
  76834. _super.prototype.dispose.call(this, camera);
  76835. };
  76836. return RefractionPostProcess;
  76837. }(BABYLON.PostProcess));
  76838. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76839. })(BABYLON || (BABYLON = {}));
  76840. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76841. var BABYLON;
  76842. (function (BABYLON) {
  76843. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76844. __extends(BlackAndWhitePostProcess, _super);
  76845. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76846. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76847. _this.degree = 1;
  76848. _this.onApplyObservable.add(function (effect) {
  76849. effect.setFloat("degree", _this.degree);
  76850. });
  76851. return _this;
  76852. }
  76853. return BlackAndWhitePostProcess;
  76854. }(BABYLON.PostProcess));
  76855. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76856. })(BABYLON || (BABYLON = {}));
  76857. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76858. var BABYLON;
  76859. (function (BABYLON) {
  76860. /**
  76861. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76862. * input texture to perform effects such as edge detection or sharpening
  76863. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76864. */
  76865. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76866. __extends(ConvolutionPostProcess, _super);
  76867. /**
  76868. * Creates a new instance ConvolutionPostProcess
  76869. * @param name The name of the effect.
  76870. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76871. * @param options The required width/height ratio to downsize to before computing the render pass.
  76872. * @param camera The camera to apply the render pass to.
  76873. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76874. * @param engine The engine which the post process will be applied. (default: current engine)
  76875. * @param reusable If the post process can be reused on the same frame. (default: false)
  76876. * @param textureType Type of textures used when performing the post process. (default: 0)
  76877. */
  76878. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76879. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76880. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76881. _this.kernel = kernel;
  76882. _this.onApply = function (effect) {
  76883. effect.setFloat2("screenSize", _this.width, _this.height);
  76884. effect.setArray("kernel", _this.kernel);
  76885. };
  76886. return _this;
  76887. }
  76888. // Statics
  76889. /**
  76890. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76891. */
  76892. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76893. /**
  76894. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76895. */
  76896. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76897. /**
  76898. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76899. */
  76900. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76901. /**
  76902. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76903. */
  76904. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76905. /**
  76906. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76907. */
  76908. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76909. /**
  76910. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76911. */
  76912. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76913. return ConvolutionPostProcess;
  76914. }(BABYLON.PostProcess));
  76915. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76916. })(BABYLON || (BABYLON = {}));
  76917. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76918. var BABYLON;
  76919. (function (BABYLON) {
  76920. var FilterPostProcess = /** @class */ (function (_super) {
  76921. __extends(FilterPostProcess, _super);
  76922. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76923. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76924. _this.kernelMatrix = kernelMatrix;
  76925. _this.onApply = function (effect) {
  76926. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76927. };
  76928. return _this;
  76929. }
  76930. return FilterPostProcess;
  76931. }(BABYLON.PostProcess));
  76932. BABYLON.FilterPostProcess = FilterPostProcess;
  76933. })(BABYLON || (BABYLON = {}));
  76934. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76935. var BABYLON;
  76936. (function (BABYLON) {
  76937. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76938. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76939. __extends(VolumetricLightScatteringPostProcess, _super);
  76940. /**
  76941. * @constructor
  76942. * @param {string} name - The post-process name
  76943. * @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)
  76944. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76945. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76946. * @param {number} samples - The post-process quality, default 100
  76947. * @param {number} samplingMode - The post-process filtering mode
  76948. * @param {BABYLON.Engine} engine - The babylon engine
  76949. * @param {boolean} reusable - If the post-process is reusable
  76950. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76951. */
  76952. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76953. if (samples === void 0) { samples = 100; }
  76954. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76955. 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;
  76956. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76957. /**
  76958. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76959. */
  76960. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76961. /**
  76962. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76963. */
  76964. _this.useCustomMeshPosition = false;
  76965. /**
  76966. * If the post-process should inverse the light scattering direction
  76967. */
  76968. _this.invert = true;
  76969. /**
  76970. * Array containing the excluded meshes not rendered in the internal pass
  76971. */
  76972. _this.excludedMeshes = new Array();
  76973. /**
  76974. * Controls the overall intensity of the post-process
  76975. */
  76976. _this.exposure = 0.3;
  76977. /**
  76978. * Dissipates each sample's contribution in range [0, 1]
  76979. */
  76980. _this.decay = 0.96815;
  76981. /**
  76982. * Controls the overall intensity of each sample
  76983. */
  76984. _this.weight = 0.58767;
  76985. /**
  76986. * Controls the density of each sample
  76987. */
  76988. _this.density = 0.926;
  76989. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76990. engine = scene.getEngine();
  76991. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76992. // Configure mesh
  76993. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76994. // Configure
  76995. _this._createPass(scene, ratio.passRatio || ratio);
  76996. _this.onActivate = function (camera) {
  76997. if (!_this.isSupported) {
  76998. _this.dispose(camera);
  76999. }
  77000. _this.onActivate = null;
  77001. };
  77002. _this.onApplyObservable.add(function (effect) {
  77003. _this._updateMeshScreenCoordinates(scene);
  77004. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77005. effect.setFloat("exposure", _this.exposure);
  77006. effect.setFloat("decay", _this.decay);
  77007. effect.setFloat("weight", _this.weight);
  77008. effect.setFloat("density", _this.density);
  77009. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77010. });
  77011. return _this;
  77012. }
  77013. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77014. get: function () {
  77015. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77016. return false;
  77017. },
  77018. set: function (useDiffuseColor) {
  77019. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77020. },
  77021. enumerable: true,
  77022. configurable: true
  77023. });
  77024. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77025. return "VolumetricLightScatteringPostProcess";
  77026. };
  77027. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77028. var mesh = subMesh.getMesh();
  77029. // Render this.mesh as default
  77030. if (mesh === this.mesh && mesh.material) {
  77031. return mesh.material.isReady(mesh);
  77032. }
  77033. var defines = [];
  77034. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77035. var material = subMesh.getMaterial();
  77036. // Alpha test
  77037. if (material) {
  77038. if (material.needAlphaTesting()) {
  77039. defines.push("#define ALPHATEST");
  77040. }
  77041. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77042. attribs.push(BABYLON.VertexBuffer.UVKind);
  77043. defines.push("#define UV1");
  77044. }
  77045. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77046. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77047. defines.push("#define UV2");
  77048. }
  77049. }
  77050. // Bones
  77051. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77052. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77053. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77054. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77055. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77056. }
  77057. else {
  77058. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77059. }
  77060. // Instances
  77061. if (useInstances) {
  77062. defines.push("#define INSTANCES");
  77063. attribs.push("world0");
  77064. attribs.push("world1");
  77065. attribs.push("world2");
  77066. attribs.push("world3");
  77067. }
  77068. // Get correct effect
  77069. var join = defines.join("\n");
  77070. if (this._cachedDefines !== join) {
  77071. this._cachedDefines = join;
  77072. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77073. }
  77074. return this._volumetricLightScatteringPass.isReady();
  77075. };
  77076. /**
  77077. * Sets the new light position for light scattering effect
  77078. * @param {BABYLON.Vector3} The new custom light position
  77079. */
  77080. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77081. this.customMeshPosition = position;
  77082. };
  77083. /**
  77084. * Returns the light position for light scattering effect
  77085. * @return {BABYLON.Vector3} The custom light position
  77086. */
  77087. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77088. return this.customMeshPosition;
  77089. };
  77090. /**
  77091. * Disposes the internal assets and detaches the post-process from the camera
  77092. */
  77093. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77094. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77095. if (rttIndex !== -1) {
  77096. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77097. }
  77098. this._volumetricLightScatteringRTT.dispose();
  77099. _super.prototype.dispose.call(this, camera);
  77100. };
  77101. /**
  77102. * Returns the render target texture used by the post-process
  77103. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77104. */
  77105. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77106. return this._volumetricLightScatteringRTT;
  77107. };
  77108. // Private methods
  77109. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77110. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77111. return true;
  77112. }
  77113. return false;
  77114. };
  77115. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77116. var _this = this;
  77117. var engine = scene.getEngine();
  77118. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77119. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77120. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77121. this._volumetricLightScatteringRTT.renderList = null;
  77122. this._volumetricLightScatteringRTT.renderParticles = false;
  77123. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77124. var camera = this.getCamera();
  77125. if (camera) {
  77126. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77127. }
  77128. else {
  77129. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77130. }
  77131. // Custom render function for submeshes
  77132. var renderSubMesh = function (subMesh) {
  77133. var mesh = subMesh.getRenderingMesh();
  77134. if (_this._meshExcluded(mesh)) {
  77135. return;
  77136. }
  77137. var material = subMesh.getMaterial();
  77138. if (!material) {
  77139. return;
  77140. }
  77141. var scene = mesh.getScene();
  77142. var engine = scene.getEngine();
  77143. // Culling
  77144. engine.setState(material.backFaceCulling);
  77145. // Managing instances
  77146. var batch = mesh._getInstancesRenderList(subMesh._id);
  77147. if (batch.mustReturn) {
  77148. return;
  77149. }
  77150. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77151. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77152. var effect = _this._volumetricLightScatteringPass;
  77153. if (mesh === _this.mesh) {
  77154. if (subMesh.effect) {
  77155. effect = subMesh.effect;
  77156. }
  77157. else {
  77158. effect = material.getEffect();
  77159. }
  77160. }
  77161. engine.enableEffect(effect);
  77162. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77163. if (mesh === _this.mesh) {
  77164. material.bind(mesh.getWorldMatrix(), mesh);
  77165. }
  77166. else {
  77167. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77168. // Alpha test
  77169. if (material && material.needAlphaTesting()) {
  77170. var alphaTexture = material.getAlphaTestTexture();
  77171. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77172. if (alphaTexture) {
  77173. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77174. }
  77175. }
  77176. // Bones
  77177. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77178. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77179. }
  77180. }
  77181. // Draw
  77182. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77183. }
  77184. };
  77185. // Render target texture callbacks
  77186. var savedSceneClearColor;
  77187. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77188. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77189. savedSceneClearColor = scene.clearColor;
  77190. scene.clearColor = sceneClearColor;
  77191. });
  77192. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77193. scene.clearColor = savedSceneClearColor;
  77194. });
  77195. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77196. var engine = scene.getEngine();
  77197. var index;
  77198. if (depthOnlySubMeshes.length) {
  77199. engine.setColorWrite(false);
  77200. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77201. renderSubMesh(depthOnlySubMeshes.data[index]);
  77202. }
  77203. engine.setColorWrite(true);
  77204. }
  77205. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77206. renderSubMesh(opaqueSubMeshes.data[index]);
  77207. }
  77208. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77209. renderSubMesh(alphaTestSubMeshes.data[index]);
  77210. }
  77211. if (transparentSubMeshes.length) {
  77212. // Sort sub meshes
  77213. for (index = 0; index < transparentSubMeshes.length; index++) {
  77214. var submesh = transparentSubMeshes.data[index];
  77215. var boundingInfo = submesh.getBoundingInfo();
  77216. if (boundingInfo && scene.activeCamera) {
  77217. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77218. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77219. }
  77220. }
  77221. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77222. sortedArray.sort(function (a, b) {
  77223. // Alpha index first
  77224. if (a._alphaIndex > b._alphaIndex) {
  77225. return 1;
  77226. }
  77227. if (a._alphaIndex < b._alphaIndex) {
  77228. return -1;
  77229. }
  77230. // Then distance to camera
  77231. if (a._distanceToCamera < b._distanceToCamera) {
  77232. return 1;
  77233. }
  77234. if (a._distanceToCamera > b._distanceToCamera) {
  77235. return -1;
  77236. }
  77237. return 0;
  77238. });
  77239. // Render sub meshes
  77240. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77241. for (index = 0; index < sortedArray.length; index++) {
  77242. renderSubMesh(sortedArray[index]);
  77243. }
  77244. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77245. }
  77246. };
  77247. };
  77248. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77249. var transform = scene.getTransformMatrix();
  77250. var meshPosition;
  77251. if (this.useCustomMeshPosition) {
  77252. meshPosition = this.customMeshPosition;
  77253. }
  77254. else if (this.attachedNode) {
  77255. meshPosition = this.attachedNode.position;
  77256. }
  77257. else {
  77258. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77259. }
  77260. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77261. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77262. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77263. if (this.invert)
  77264. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77265. };
  77266. // Static methods
  77267. /**
  77268. * Creates a default mesh for the Volumeric Light Scattering post-process
  77269. * @param {string} The mesh name
  77270. * @param {BABYLON.Scene} The scene where to create the mesh
  77271. * @return {BABYLON.Mesh} the default mesh
  77272. */
  77273. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77274. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77275. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77276. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77277. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77278. mesh.material = material;
  77279. return mesh;
  77280. };
  77281. __decorate([
  77282. BABYLON.serializeAsVector3()
  77283. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77284. __decorate([
  77285. BABYLON.serialize()
  77286. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77287. __decorate([
  77288. BABYLON.serialize()
  77289. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77290. __decorate([
  77291. BABYLON.serializeAsMeshReference()
  77292. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77293. __decorate([
  77294. BABYLON.serialize()
  77295. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77296. __decorate([
  77297. BABYLON.serialize()
  77298. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77299. __decorate([
  77300. BABYLON.serialize()
  77301. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77302. __decorate([
  77303. BABYLON.serialize()
  77304. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77305. __decorate([
  77306. BABYLON.serialize()
  77307. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77308. return VolumetricLightScatteringPostProcess;
  77309. }(BABYLON.PostProcess));
  77310. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77311. })(BABYLON || (BABYLON = {}));
  77312. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77313. //
  77314. // This post-process allows the modification of rendered colors by using
  77315. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77316. //
  77317. // The object needs to be provided an url to a texture containing the color
  77318. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77319. // Use an image editing software to tweak the LUT to match your needs.
  77320. //
  77321. // For an example of a color LUT, see here:
  77322. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77323. // For explanations on color grading, see here:
  77324. // http://udn.epicgames.com/Three/ColorGrading.html
  77325. //
  77326. var BABYLON;
  77327. (function (BABYLON) {
  77328. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77329. __extends(ColorCorrectionPostProcess, _super);
  77330. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77331. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77332. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77333. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77334. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77335. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77336. _this.onApply = function (effect) {
  77337. effect.setTexture("colorTable", _this._colorTableTexture);
  77338. };
  77339. return _this;
  77340. }
  77341. return ColorCorrectionPostProcess;
  77342. }(BABYLON.PostProcess));
  77343. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77344. })(BABYLON || (BABYLON = {}));
  77345. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77346. var BABYLON;
  77347. (function (BABYLON) {
  77348. /** Defines operator used for tonemapping */
  77349. var TonemappingOperator;
  77350. (function (TonemappingOperator) {
  77351. /** Hable */
  77352. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77353. /** Reinhard */
  77354. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77355. /** HejiDawson */
  77356. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77357. /** Photographic */
  77358. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77359. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77360. ;
  77361. /**
  77362. * Defines a post process to apply tone mapping
  77363. */
  77364. var TonemapPostProcess = /** @class */ (function (_super) {
  77365. __extends(TonemapPostProcess, _super);
  77366. /**
  77367. * Creates a new TonemapPostProcess
  77368. * @param name defines the name of the postprocess
  77369. * @param _operator defines the operator to use
  77370. * @param exposureAdjustment defines the required exposure adjustement
  77371. * @param camera defines the camera to use (can be null)
  77372. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77373. * @param engine defines the hosting engine (can be ignore if camera is set)
  77374. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77375. */
  77376. function TonemapPostProcess(name, _operator,
  77377. /** Defines the required exposure adjustement */
  77378. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77379. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77380. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77381. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77382. _this._operator = _operator;
  77383. _this.exposureAdjustment = exposureAdjustment;
  77384. var defines = "#define ";
  77385. if (_this._operator === TonemappingOperator.Hable)
  77386. defines += "HABLE_TONEMAPPING";
  77387. else if (_this._operator === TonemappingOperator.Reinhard)
  77388. defines += "REINHARD_TONEMAPPING";
  77389. else if (_this._operator === TonemappingOperator.HejiDawson)
  77390. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77391. else if (_this._operator === TonemappingOperator.Photographic)
  77392. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77393. //sadly a second call to create the effect.
  77394. _this.updateEffect(defines);
  77395. _this.onApply = function (effect) {
  77396. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77397. };
  77398. return _this;
  77399. }
  77400. return TonemapPostProcess;
  77401. }(BABYLON.PostProcess));
  77402. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77403. })(BABYLON || (BABYLON = {}));
  77404. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77405. var BABYLON;
  77406. (function (BABYLON) {
  77407. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77408. __extends(DisplayPassPostProcess, _super);
  77409. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77410. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77411. }
  77412. return DisplayPassPostProcess;
  77413. }(BABYLON.PostProcess));
  77414. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77415. })(BABYLON || (BABYLON = {}));
  77416. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77417. var BABYLON;
  77418. (function (BABYLON) {
  77419. var HighlightsPostProcess = /** @class */ (function (_super) {
  77420. __extends(HighlightsPostProcess, _super);
  77421. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77422. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77423. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77424. }
  77425. return HighlightsPostProcess;
  77426. }(BABYLON.PostProcess));
  77427. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77428. })(BABYLON || (BABYLON = {}));
  77429. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77430. var BABYLON;
  77431. (function (BABYLON) {
  77432. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77433. __extends(ImageProcessingPostProcess, _super);
  77434. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77435. if (camera === void 0) { camera = null; }
  77436. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77437. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77438. _this._fromLinearSpace = true;
  77439. /**
  77440. * Defines cache preventing GC.
  77441. */
  77442. _this._defines = {
  77443. IMAGEPROCESSING: false,
  77444. VIGNETTE: false,
  77445. VIGNETTEBLENDMODEMULTIPLY: false,
  77446. VIGNETTEBLENDMODEOPAQUE: false,
  77447. TONEMAPPING: false,
  77448. CONTRAST: false,
  77449. COLORCURVES: false,
  77450. COLORGRADING: false,
  77451. COLORGRADING3D: false,
  77452. FROMLINEARSPACE: false,
  77453. SAMPLER3DGREENDEPTH: false,
  77454. SAMPLER3DBGRMAP: false,
  77455. IMAGEPROCESSINGPOSTPROCESS: false,
  77456. EXPOSURE: false,
  77457. };
  77458. // Setup the configuration as forced by the constructor. This would then not force the
  77459. // scene materials output in linear space and let untouched the default forward pass.
  77460. if (imageProcessingConfiguration) {
  77461. imageProcessingConfiguration.applyByPostProcess = true;
  77462. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77463. // This will cause the shader to be compiled
  77464. _this.fromLinearSpace = false;
  77465. }
  77466. // Setup the default processing configuration to the scene.
  77467. else {
  77468. _this._attachImageProcessingConfiguration(null, true);
  77469. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77470. }
  77471. _this.onApply = function (effect) {
  77472. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77473. };
  77474. return _this;
  77475. }
  77476. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77477. /**
  77478. * Gets the image processing configuration used either in this material.
  77479. */
  77480. get: function () {
  77481. return this._imageProcessingConfiguration;
  77482. },
  77483. /**
  77484. * Sets the Default image processing configuration used either in the this material.
  77485. *
  77486. * If sets to null, the scene one is in use.
  77487. */
  77488. set: function (value) {
  77489. this._attachImageProcessingConfiguration(value);
  77490. },
  77491. enumerable: true,
  77492. configurable: true
  77493. });
  77494. /**
  77495. * Attaches a new image processing configuration to the PBR Material.
  77496. * @param configuration
  77497. */
  77498. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77499. var _this = this;
  77500. if (doNotBuild === void 0) { doNotBuild = false; }
  77501. if (configuration === this._imageProcessingConfiguration) {
  77502. return;
  77503. }
  77504. // Detaches observer.
  77505. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77506. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77507. }
  77508. // Pick the scene configuration if needed.
  77509. if (!configuration) {
  77510. var scene = null;
  77511. var engine = this.getEngine();
  77512. var camera = this.getCamera();
  77513. if (camera) {
  77514. scene = camera.getScene();
  77515. }
  77516. else if (engine && engine.scenes) {
  77517. var scenes = engine.scenes;
  77518. scene = scenes[scenes.length - 1];
  77519. }
  77520. else {
  77521. scene = BABYLON.Engine.LastCreatedScene;
  77522. }
  77523. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77524. }
  77525. else {
  77526. this._imageProcessingConfiguration = configuration;
  77527. }
  77528. // Attaches observer.
  77529. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77530. _this._updateParameters();
  77531. });
  77532. // Ensure the effect will be rebuilt.
  77533. if (!doNotBuild) {
  77534. this._updateParameters();
  77535. }
  77536. };
  77537. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77538. /**
  77539. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77540. */
  77541. get: function () {
  77542. return this.imageProcessingConfiguration.colorCurves;
  77543. },
  77544. /**
  77545. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77546. */
  77547. set: function (value) {
  77548. this.imageProcessingConfiguration.colorCurves = value;
  77549. },
  77550. enumerable: true,
  77551. configurable: true
  77552. });
  77553. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77554. /**
  77555. * Gets wether the color curves effect is enabled.
  77556. */
  77557. get: function () {
  77558. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77559. },
  77560. /**
  77561. * Sets wether the color curves effect is enabled.
  77562. */
  77563. set: function (value) {
  77564. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77565. },
  77566. enumerable: true,
  77567. configurable: true
  77568. });
  77569. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77570. /**
  77571. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77572. */
  77573. get: function () {
  77574. return this.imageProcessingConfiguration.colorGradingTexture;
  77575. },
  77576. /**
  77577. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77578. */
  77579. set: function (value) {
  77580. this.imageProcessingConfiguration.colorGradingTexture = value;
  77581. },
  77582. enumerable: true,
  77583. configurable: true
  77584. });
  77585. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77586. /**
  77587. * Gets wether the color grading effect is enabled.
  77588. */
  77589. get: function () {
  77590. return this.imageProcessingConfiguration.colorGradingEnabled;
  77591. },
  77592. /**
  77593. * Gets wether the color grading effect is enabled.
  77594. */
  77595. set: function (value) {
  77596. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77597. },
  77598. enumerable: true,
  77599. configurable: true
  77600. });
  77601. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77602. /**
  77603. * Gets exposure used in the effect.
  77604. */
  77605. get: function () {
  77606. return this.imageProcessingConfiguration.exposure;
  77607. },
  77608. /**
  77609. * Sets exposure used in the effect.
  77610. */
  77611. set: function (value) {
  77612. this.imageProcessingConfiguration.exposure = value;
  77613. },
  77614. enumerable: true,
  77615. configurable: true
  77616. });
  77617. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77618. /**
  77619. * Gets wether tonemapping is enabled or not.
  77620. */
  77621. get: function () {
  77622. return this._imageProcessingConfiguration.toneMappingEnabled;
  77623. },
  77624. /**
  77625. * Sets wether tonemapping is enabled or not
  77626. */
  77627. set: function (value) {
  77628. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77629. },
  77630. enumerable: true,
  77631. configurable: true
  77632. });
  77633. ;
  77634. ;
  77635. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77636. /**
  77637. * Gets contrast used in the effect.
  77638. */
  77639. get: function () {
  77640. return this.imageProcessingConfiguration.contrast;
  77641. },
  77642. /**
  77643. * Sets contrast used in the effect.
  77644. */
  77645. set: function (value) {
  77646. this.imageProcessingConfiguration.contrast = value;
  77647. },
  77648. enumerable: true,
  77649. configurable: true
  77650. });
  77651. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77652. /**
  77653. * Gets Vignette stretch size.
  77654. */
  77655. get: function () {
  77656. return this.imageProcessingConfiguration.vignetteStretch;
  77657. },
  77658. /**
  77659. * Sets Vignette stretch size.
  77660. */
  77661. set: function (value) {
  77662. this.imageProcessingConfiguration.vignetteStretch = value;
  77663. },
  77664. enumerable: true,
  77665. configurable: true
  77666. });
  77667. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77668. /**
  77669. * Gets Vignette centre X Offset.
  77670. */
  77671. get: function () {
  77672. return this.imageProcessingConfiguration.vignetteCentreX;
  77673. },
  77674. /**
  77675. * Sets Vignette centre X Offset.
  77676. */
  77677. set: function (value) {
  77678. this.imageProcessingConfiguration.vignetteCentreX = value;
  77679. },
  77680. enumerable: true,
  77681. configurable: true
  77682. });
  77683. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77684. /**
  77685. * Gets Vignette centre Y Offset.
  77686. */
  77687. get: function () {
  77688. return this.imageProcessingConfiguration.vignetteCentreY;
  77689. },
  77690. /**
  77691. * Sets Vignette centre Y Offset.
  77692. */
  77693. set: function (value) {
  77694. this.imageProcessingConfiguration.vignetteCentreY = value;
  77695. },
  77696. enumerable: true,
  77697. configurable: true
  77698. });
  77699. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77700. /**
  77701. * Gets Vignette weight or intensity of the vignette effect.
  77702. */
  77703. get: function () {
  77704. return this.imageProcessingConfiguration.vignetteWeight;
  77705. },
  77706. /**
  77707. * Sets Vignette weight or intensity of the vignette effect.
  77708. */
  77709. set: function (value) {
  77710. this.imageProcessingConfiguration.vignetteWeight = value;
  77711. },
  77712. enumerable: true,
  77713. configurable: true
  77714. });
  77715. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77716. /**
  77717. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77718. * if vignetteEnabled is set to true.
  77719. */
  77720. get: function () {
  77721. return this.imageProcessingConfiguration.vignetteColor;
  77722. },
  77723. /**
  77724. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77725. * if vignetteEnabled is set to true.
  77726. */
  77727. set: function (value) {
  77728. this.imageProcessingConfiguration.vignetteColor = value;
  77729. },
  77730. enumerable: true,
  77731. configurable: true
  77732. });
  77733. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77734. /**
  77735. * Gets Camera field of view used by the Vignette effect.
  77736. */
  77737. get: function () {
  77738. return this.imageProcessingConfiguration.vignetteCameraFov;
  77739. },
  77740. /**
  77741. * Sets Camera field of view used by the Vignette effect.
  77742. */
  77743. set: function (value) {
  77744. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77745. },
  77746. enumerable: true,
  77747. configurable: true
  77748. });
  77749. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77750. /**
  77751. * Gets the vignette blend mode allowing different kind of effect.
  77752. */
  77753. get: function () {
  77754. return this.imageProcessingConfiguration.vignetteBlendMode;
  77755. },
  77756. /**
  77757. * Sets the vignette blend mode allowing different kind of effect.
  77758. */
  77759. set: function (value) {
  77760. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77761. },
  77762. enumerable: true,
  77763. configurable: true
  77764. });
  77765. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77766. /**
  77767. * Gets wether the vignette effect is enabled.
  77768. */
  77769. get: function () {
  77770. return this.imageProcessingConfiguration.vignetteEnabled;
  77771. },
  77772. /**
  77773. * Sets wether the vignette effect is enabled.
  77774. */
  77775. set: function (value) {
  77776. this.imageProcessingConfiguration.vignetteEnabled = value;
  77777. },
  77778. enumerable: true,
  77779. configurable: true
  77780. });
  77781. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77782. /**
  77783. * Gets wether the input of the processing is in Gamma or Linear Space.
  77784. */
  77785. get: function () {
  77786. return this._fromLinearSpace;
  77787. },
  77788. /**
  77789. * Sets wether the input of the processing is in Gamma or Linear Space.
  77790. */
  77791. set: function (value) {
  77792. if (this._fromLinearSpace === value) {
  77793. return;
  77794. }
  77795. this._fromLinearSpace = value;
  77796. this._updateParameters();
  77797. },
  77798. enumerable: true,
  77799. configurable: true
  77800. });
  77801. ImageProcessingPostProcess.prototype.getClassName = function () {
  77802. return "ImageProcessingPostProcess";
  77803. };
  77804. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77805. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77806. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77807. var defines = "";
  77808. for (var define in this._defines) {
  77809. if (this._defines[define]) {
  77810. defines += "#define " + define + ";\r\n";
  77811. }
  77812. }
  77813. var samplers = ["textureSampler"];
  77814. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77815. var uniforms = ["scale"];
  77816. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77817. this.updateEffect(defines, uniforms, samplers);
  77818. };
  77819. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77820. _super.prototype.dispose.call(this, camera);
  77821. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77822. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77823. }
  77824. this.imageProcessingConfiguration.applyByPostProcess = false;
  77825. };
  77826. __decorate([
  77827. BABYLON.serialize()
  77828. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77829. return ImageProcessingPostProcess;
  77830. }(BABYLON.PostProcess));
  77831. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77832. })(BABYLON || (BABYLON = {}));
  77833. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77834. var BABYLON;
  77835. (function (BABYLON) {
  77836. /**
  77837. * Class used to store bone information
  77838. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77839. */
  77840. var Bone = /** @class */ (function (_super) {
  77841. __extends(Bone, _super);
  77842. /**
  77843. * Create a new bone
  77844. * @param name defines the bone name
  77845. * @param skeleton defines the parent skeleton
  77846. * @param parentBone defines the parent (can be null if the bone is the root)
  77847. * @param localMatrix defines the local matrix
  77848. * @param restPose defines the rest pose matrix
  77849. * @param baseMatrix defines the base matrix
  77850. * @param index defines index of the bone in the hiearchy
  77851. */
  77852. function Bone(
  77853. /**
  77854. * defines the bone name
  77855. */
  77856. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77857. if (parentBone === void 0) { parentBone = null; }
  77858. if (localMatrix === void 0) { localMatrix = null; }
  77859. if (restPose === void 0) { restPose = null; }
  77860. if (baseMatrix === void 0) { baseMatrix = null; }
  77861. if (index === void 0) { index = null; }
  77862. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77863. _this.name = name;
  77864. /**
  77865. * Gets the list of child bones
  77866. */
  77867. _this.children = new Array();
  77868. /** Gets the animations associated with this bone */
  77869. _this.animations = new Array();
  77870. /**
  77871. * @hidden Internal only
  77872. * Set this value to map this bone to a different index in the transform matrices
  77873. * Set this value to -1 to exclude the bone from the transform matrices
  77874. */
  77875. _this._index = null;
  77876. _this._absoluteTransform = new BABYLON.Matrix();
  77877. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77878. _this._scalingDeterminant = 1;
  77879. _this._worldTransform = new BABYLON.Matrix();
  77880. _this._needToDecompose = true;
  77881. _this._needToCompose = false;
  77882. _this._skeleton = skeleton;
  77883. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77884. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77885. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77886. _this._index = index;
  77887. skeleton.bones.push(_this);
  77888. _this.setParent(parentBone, false);
  77889. if (baseMatrix || localMatrix) {
  77890. _this._updateDifferenceMatrix();
  77891. }
  77892. return _this;
  77893. }
  77894. Object.defineProperty(Bone.prototype, "_matrix", {
  77895. /** @hidden */
  77896. get: function () {
  77897. this._compose();
  77898. return this._localMatrix;
  77899. },
  77900. /** @hidden */
  77901. set: function (value) {
  77902. this._localMatrix.copyFrom(value);
  77903. this._needToDecompose = true;
  77904. },
  77905. enumerable: true,
  77906. configurable: true
  77907. });
  77908. // Members
  77909. /**
  77910. * Gets the parent skeleton
  77911. * @returns a skeleton
  77912. */
  77913. Bone.prototype.getSkeleton = function () {
  77914. return this._skeleton;
  77915. };
  77916. /**
  77917. * Gets parent bone
  77918. * @returns a bone or null if the bone is the root of the bone hierarchy
  77919. */
  77920. Bone.prototype.getParent = function () {
  77921. return this._parent;
  77922. };
  77923. /**
  77924. * Sets the parent bone
  77925. * @param parent defines the parent (can be null if the bone is the root)
  77926. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77927. */
  77928. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77929. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77930. if (this._parent === parent) {
  77931. return;
  77932. }
  77933. if (this._parent) {
  77934. var index = this._parent.children.indexOf(this);
  77935. if (index !== -1) {
  77936. this._parent.children.splice(index, 1);
  77937. }
  77938. }
  77939. this._parent = parent;
  77940. if (this._parent) {
  77941. this._parent.children.push(this);
  77942. }
  77943. if (updateDifferenceMatrix) {
  77944. this._updateDifferenceMatrix();
  77945. }
  77946. this.markAsDirty();
  77947. };
  77948. /**
  77949. * Gets the local matrix
  77950. * @returns a matrix
  77951. */
  77952. Bone.prototype.getLocalMatrix = function () {
  77953. this._compose();
  77954. return this._localMatrix;
  77955. };
  77956. /**
  77957. * Gets the base matrix (initial matrix which remains unchanged)
  77958. * @returns a matrix
  77959. */
  77960. Bone.prototype.getBaseMatrix = function () {
  77961. return this._baseMatrix;
  77962. };
  77963. /**
  77964. * Gets the rest pose matrix
  77965. * @returns a matrix
  77966. */
  77967. Bone.prototype.getRestPose = function () {
  77968. return this._restPose;
  77969. };
  77970. /**
  77971. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77972. */
  77973. Bone.prototype.getWorldMatrix = function () {
  77974. return this._worldTransform;
  77975. };
  77976. /**
  77977. * Sets the local matrix to rest pose matrix
  77978. */
  77979. Bone.prototype.returnToRest = function () {
  77980. this.updateMatrix(this._restPose.clone());
  77981. };
  77982. /**
  77983. * Gets the inverse of the absolute transform matrix.
  77984. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77985. * @returns a matrix
  77986. */
  77987. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77988. return this._invertedAbsoluteTransform;
  77989. };
  77990. /**
  77991. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77992. * @returns a matrix
  77993. */
  77994. Bone.prototype.getAbsoluteTransform = function () {
  77995. return this._absoluteTransform;
  77996. };
  77997. Object.defineProperty(Bone.prototype, "position", {
  77998. // Properties (matches AbstractMesh properties)
  77999. /** Gets or sets current position (in local space) */
  78000. get: function () {
  78001. this._decompose();
  78002. return this._localPosition;
  78003. },
  78004. set: function (newPosition) {
  78005. this._decompose();
  78006. this._localPosition.copyFrom(newPosition);
  78007. this._markAsDirtyAndCompose();
  78008. },
  78009. enumerable: true,
  78010. configurable: true
  78011. });
  78012. Object.defineProperty(Bone.prototype, "rotation", {
  78013. /** Gets or sets current rotation (in local space) */
  78014. get: function () {
  78015. return this.getRotation();
  78016. },
  78017. set: function (newRotation) {
  78018. this.setRotation(newRotation);
  78019. },
  78020. enumerable: true,
  78021. configurable: true
  78022. });
  78023. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78024. /** Gets or sets current rotation quaternion (in local space) */
  78025. get: function () {
  78026. this._decompose();
  78027. return this._localRotation;
  78028. },
  78029. set: function (newRotation) {
  78030. this.setRotationQuaternion(newRotation);
  78031. },
  78032. enumerable: true,
  78033. configurable: true
  78034. });
  78035. Object.defineProperty(Bone.prototype, "scaling", {
  78036. /** Gets or sets current scaling (in local space) */
  78037. get: function () {
  78038. return this.getScale();
  78039. },
  78040. set: function (newScaling) {
  78041. this.setScale(newScaling);
  78042. },
  78043. enumerable: true,
  78044. configurable: true
  78045. });
  78046. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78047. /**
  78048. * Gets the animation properties override
  78049. */
  78050. get: function () {
  78051. return this._skeleton.animationPropertiesOverride;
  78052. },
  78053. enumerable: true,
  78054. configurable: true
  78055. });
  78056. // Methods
  78057. Bone.prototype._decompose = function () {
  78058. if (!this._needToDecompose) {
  78059. return;
  78060. }
  78061. this._needToDecompose = false;
  78062. if (!this._localScaling) {
  78063. this._localScaling = BABYLON.Vector3.Zero();
  78064. this._localRotation = BABYLON.Quaternion.Zero();
  78065. this._localPosition = BABYLON.Vector3.Zero();
  78066. }
  78067. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78068. };
  78069. Bone.prototype._compose = function () {
  78070. if (!this._needToCompose) {
  78071. return;
  78072. }
  78073. this._needToCompose = false;
  78074. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78075. };
  78076. /**
  78077. * Update the base and local matrices
  78078. * @param matrix defines the new base or local matrix
  78079. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78080. * @param updateLocalMatrix defines if the local matrix should be updated
  78081. */
  78082. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78083. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78084. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78085. this._baseMatrix.copyFrom(matrix);
  78086. if (updateDifferenceMatrix) {
  78087. this._updateDifferenceMatrix();
  78088. }
  78089. if (updateLocalMatrix) {
  78090. this._localMatrix.copyFrom(matrix);
  78091. this._markAsDirtyAndDecompose();
  78092. }
  78093. else {
  78094. this.markAsDirty();
  78095. }
  78096. };
  78097. /** @hidden */
  78098. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78099. if (updateChildren === void 0) { updateChildren = true; }
  78100. if (!rootMatrix) {
  78101. rootMatrix = this._baseMatrix;
  78102. }
  78103. if (this._parent) {
  78104. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78105. }
  78106. else {
  78107. this._absoluteTransform.copyFrom(rootMatrix);
  78108. }
  78109. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78110. if (updateChildren) {
  78111. for (var index = 0; index < this.children.length; index++) {
  78112. this.children[index]._updateDifferenceMatrix();
  78113. }
  78114. }
  78115. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78116. };
  78117. /**
  78118. * Flag the bone as dirty (Forcing it to update everything)
  78119. */
  78120. Bone.prototype.markAsDirty = function () {
  78121. this._currentRenderId++;
  78122. this._childRenderId++;
  78123. this._skeleton._markAsDirty();
  78124. };
  78125. Bone.prototype._markAsDirtyAndCompose = function () {
  78126. this.markAsDirty();
  78127. this._needToCompose = true;
  78128. };
  78129. Bone.prototype._markAsDirtyAndDecompose = function () {
  78130. this.markAsDirty();
  78131. this._needToDecompose = true;
  78132. };
  78133. /**
  78134. * Copy an animation range from another bone
  78135. * @param source defines the source bone
  78136. * @param rangeName defines the range name to copy
  78137. * @param frameOffset defines the frame offset
  78138. * @param rescaleAsRequired defines if rescaling must be applied if required
  78139. * @param skelDimensionsRatio defines the scaling ratio
  78140. * @returns true if operation was successful
  78141. */
  78142. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78143. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78144. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78145. // all animation may be coming from a library skeleton, so may need to create animation
  78146. if (this.animations.length === 0) {
  78147. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78148. this.animations[0].setKeys([]);
  78149. }
  78150. // get animation info / verify there is such a range from the source bone
  78151. var sourceRange = source.animations[0].getRange(rangeName);
  78152. if (!sourceRange) {
  78153. return false;
  78154. }
  78155. var from = sourceRange.from;
  78156. var to = sourceRange.to;
  78157. var sourceKeys = source.animations[0].getKeys();
  78158. // rescaling prep
  78159. var sourceBoneLength = source.length;
  78160. var sourceParent = source.getParent();
  78161. var parent = this.getParent();
  78162. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78163. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78164. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78165. var destKeys = this.animations[0].getKeys();
  78166. // loop vars declaration
  78167. var orig;
  78168. var origTranslation;
  78169. var mat;
  78170. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78171. orig = sourceKeys[key];
  78172. if (orig.frame >= from && orig.frame <= to) {
  78173. if (rescaleAsRequired) {
  78174. mat = orig.value.clone();
  78175. // scale based on parent ratio, when bone has parent
  78176. if (parentScalingReqd) {
  78177. origTranslation = mat.getTranslation();
  78178. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78179. // scale based on skeleton dimension ratio when root bone, and value is passed
  78180. }
  78181. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78182. origTranslation = mat.getTranslation();
  78183. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78184. // use original when root bone, and no data for skelDimensionsRatio
  78185. }
  78186. else {
  78187. mat = orig.value;
  78188. }
  78189. }
  78190. else {
  78191. mat = orig.value;
  78192. }
  78193. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78194. }
  78195. }
  78196. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78197. return true;
  78198. };
  78199. /**
  78200. * Translate the bone in local or world space
  78201. * @param vec The amount to translate the bone
  78202. * @param space The space that the translation is in
  78203. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78204. */
  78205. Bone.prototype.translate = function (vec, space, mesh) {
  78206. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78207. var lm = this.getLocalMatrix();
  78208. if (space == BABYLON.Space.LOCAL) {
  78209. lm.m[12] += vec.x;
  78210. lm.m[13] += vec.y;
  78211. lm.m[14] += vec.z;
  78212. }
  78213. else {
  78214. var wm = null;
  78215. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78216. if (mesh) {
  78217. wm = mesh.getWorldMatrix();
  78218. }
  78219. this._skeleton.computeAbsoluteTransforms();
  78220. var tmat = Bone._tmpMats[0];
  78221. var tvec = Bone._tmpVecs[0];
  78222. if (this._parent) {
  78223. if (mesh && wm) {
  78224. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78225. tmat.multiplyToRef(wm, tmat);
  78226. }
  78227. else {
  78228. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78229. }
  78230. }
  78231. tmat.m[12] = 0;
  78232. tmat.m[13] = 0;
  78233. tmat.m[14] = 0;
  78234. tmat.invert();
  78235. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78236. lm.m[12] += tvec.x;
  78237. lm.m[13] += tvec.y;
  78238. lm.m[14] += tvec.z;
  78239. }
  78240. this._markAsDirtyAndDecompose();
  78241. };
  78242. /**
  78243. * Set the postion of the bone in local or world space
  78244. * @param position The position to set the bone
  78245. * @param space The space that the position is in
  78246. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78247. */
  78248. Bone.prototype.setPosition = function (position, space, mesh) {
  78249. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78250. var lm = this.getLocalMatrix();
  78251. if (space == BABYLON.Space.LOCAL) {
  78252. lm.m[12] = position.x;
  78253. lm.m[13] = position.y;
  78254. lm.m[14] = position.z;
  78255. }
  78256. else {
  78257. var wm = null;
  78258. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78259. if (mesh) {
  78260. wm = mesh.getWorldMatrix();
  78261. }
  78262. this._skeleton.computeAbsoluteTransforms();
  78263. var tmat = Bone._tmpMats[0];
  78264. var vec = Bone._tmpVecs[0];
  78265. if (this._parent) {
  78266. if (mesh && wm) {
  78267. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78268. tmat.multiplyToRef(wm, tmat);
  78269. }
  78270. else {
  78271. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78272. }
  78273. }
  78274. tmat.invert();
  78275. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78276. lm.m[12] = vec.x;
  78277. lm.m[13] = vec.y;
  78278. lm.m[14] = vec.z;
  78279. }
  78280. this._markAsDirtyAndDecompose();
  78281. };
  78282. /**
  78283. * Set the absolute position of the bone (world space)
  78284. * @param position The position to set the bone
  78285. * @param mesh The mesh that this bone is attached to
  78286. */
  78287. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78288. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78289. };
  78290. /**
  78291. * Scale the bone on the x, y and z axes (in local space)
  78292. * @param x The amount to scale the bone on the x axis
  78293. * @param y The amount to scale the bone on the y axis
  78294. * @param z The amount to scale the bone on the z axis
  78295. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78296. */
  78297. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78298. if (scaleChildren === void 0) { scaleChildren = false; }
  78299. var locMat = this.getLocalMatrix();
  78300. // Apply new scaling on top of current local matrix
  78301. var scaleMat = Bone._tmpMats[0];
  78302. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78303. scaleMat.multiplyToRef(locMat, locMat);
  78304. // Invert scaling matrix and apply the inverse to all children
  78305. scaleMat.invert();
  78306. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78307. var child = _a[_i];
  78308. var cm = child.getLocalMatrix();
  78309. cm.multiplyToRef(scaleMat, cm);
  78310. cm.m[12] *= x;
  78311. cm.m[13] *= y;
  78312. cm.m[14] *= z;
  78313. child._markAsDirtyAndDecompose();
  78314. }
  78315. this._markAsDirtyAndDecompose();
  78316. if (scaleChildren) {
  78317. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78318. var child = _c[_b];
  78319. child.scale(x, y, z, scaleChildren);
  78320. }
  78321. }
  78322. };
  78323. /**
  78324. * Set the bone scaling in local space
  78325. * @param scale defines the scaling vector
  78326. */
  78327. Bone.prototype.setScale = function (scale) {
  78328. this._decompose();
  78329. this._localScaling.copyFrom(scale);
  78330. this._markAsDirtyAndCompose();
  78331. };
  78332. /**
  78333. * Gets the current scaling in local space
  78334. * @returns the current scaling vector
  78335. */
  78336. Bone.prototype.getScale = function () {
  78337. this._decompose();
  78338. return this._localScaling;
  78339. };
  78340. /**
  78341. * Gets the current scaling in local space and stores it in a target vector
  78342. * @param result defines the target vector
  78343. */
  78344. Bone.prototype.getScaleToRef = function (result) {
  78345. this._decompose();
  78346. result.copyFrom(this._localScaling);
  78347. };
  78348. /**
  78349. * Set the yaw, pitch, and roll of the bone in local or world space
  78350. * @param yaw The rotation of the bone on the y axis
  78351. * @param pitch The rotation of the bone on the x axis
  78352. * @param roll The rotation of the bone on the z axis
  78353. * @param space The space that the axes of rotation are in
  78354. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78355. */
  78356. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78357. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78358. if (space === BABYLON.Space.LOCAL) {
  78359. var quat = Bone._tmpQuat;
  78360. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78361. this.setRotationQuaternion(quat, space, mesh);
  78362. return;
  78363. }
  78364. var rotMatInv = Bone._tmpMats[0];
  78365. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78366. return;
  78367. }
  78368. var rotMat = Bone._tmpMats[1];
  78369. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78370. rotMatInv.multiplyToRef(rotMat, rotMat);
  78371. this._rotateWithMatrix(rotMat, space, mesh);
  78372. };
  78373. /**
  78374. * Add a rotation to the bone on an axis in local or world space
  78375. * @param axis The axis to rotate the bone on
  78376. * @param amount The amount to rotate the bone
  78377. * @param space The space that the axis is in
  78378. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78379. */
  78380. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78381. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78382. var rmat = Bone._tmpMats[0];
  78383. rmat.m[12] = 0;
  78384. rmat.m[13] = 0;
  78385. rmat.m[14] = 0;
  78386. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78387. this._rotateWithMatrix(rmat, space, mesh);
  78388. };
  78389. /**
  78390. * Set the rotation of the bone to a particular axis angle in local or world space
  78391. * @param axis The axis to rotate the bone on
  78392. * @param angle The angle that the bone should be rotated to
  78393. * @param space The space that the axis is in
  78394. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78395. */
  78396. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78397. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78398. if (space === BABYLON.Space.LOCAL) {
  78399. var quat = Bone._tmpQuat;
  78400. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78401. this.setRotationQuaternion(quat, space, mesh);
  78402. return;
  78403. }
  78404. var rotMatInv = Bone._tmpMats[0];
  78405. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78406. return;
  78407. }
  78408. var rotMat = Bone._tmpMats[1];
  78409. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78410. rotMatInv.multiplyToRef(rotMat, rotMat);
  78411. this._rotateWithMatrix(rotMat, space, mesh);
  78412. };
  78413. /**
  78414. * Set the euler rotation of the bone in local of world space
  78415. * @param rotation The euler rotation that the bone should be set to
  78416. * @param space The space that the rotation is in
  78417. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78418. */
  78419. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78420. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78421. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78422. };
  78423. /**
  78424. * Set the quaternion rotation of the bone in local of world space
  78425. * @param quat The quaternion rotation that the bone should be set to
  78426. * @param space The space that the rotation is in
  78427. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78428. */
  78429. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78430. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78431. if (space === BABYLON.Space.LOCAL) {
  78432. this._decompose();
  78433. this._localRotation.copyFrom(quat);
  78434. this._markAsDirtyAndCompose();
  78435. return;
  78436. }
  78437. var rotMatInv = Bone._tmpMats[0];
  78438. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78439. return;
  78440. }
  78441. var rotMat = Bone._tmpMats[1];
  78442. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78443. rotMatInv.multiplyToRef(rotMat, rotMat);
  78444. this._rotateWithMatrix(rotMat, space, mesh);
  78445. };
  78446. /**
  78447. * Set the rotation matrix of the bone in local of world space
  78448. * @param rotMat The rotation matrix that the bone should be set to
  78449. * @param space The space that the rotation is in
  78450. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78451. */
  78452. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78453. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78454. if (space === BABYLON.Space.LOCAL) {
  78455. var quat = Bone._tmpQuat;
  78456. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78457. this.setRotationQuaternion(quat, space, mesh);
  78458. return;
  78459. }
  78460. var rotMatInv = Bone._tmpMats[0];
  78461. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78462. return;
  78463. }
  78464. var rotMat2 = Bone._tmpMats[1];
  78465. rotMat2.copyFrom(rotMat);
  78466. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78467. this._rotateWithMatrix(rotMat2, space, mesh);
  78468. };
  78469. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78470. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78471. var lmat = this.getLocalMatrix();
  78472. var lx = lmat.m[12];
  78473. var ly = lmat.m[13];
  78474. var lz = lmat.m[14];
  78475. var parent = this.getParent();
  78476. var parentScale = Bone._tmpMats[3];
  78477. var parentScaleInv = Bone._tmpMats[4];
  78478. if (parent && space == BABYLON.Space.WORLD) {
  78479. if (mesh) {
  78480. parentScale.copyFrom(mesh.getWorldMatrix());
  78481. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78482. }
  78483. else {
  78484. parentScale.copyFrom(parent.getAbsoluteTransform());
  78485. }
  78486. parentScaleInv.copyFrom(parentScale);
  78487. parentScaleInv.invert();
  78488. lmat.multiplyToRef(parentScale, lmat);
  78489. lmat.multiplyToRef(rmat, lmat);
  78490. lmat.multiplyToRef(parentScaleInv, lmat);
  78491. }
  78492. else {
  78493. if (space == BABYLON.Space.WORLD && mesh) {
  78494. parentScale.copyFrom(mesh.getWorldMatrix());
  78495. parentScaleInv.copyFrom(parentScale);
  78496. parentScaleInv.invert();
  78497. lmat.multiplyToRef(parentScale, lmat);
  78498. lmat.multiplyToRef(rmat, lmat);
  78499. lmat.multiplyToRef(parentScaleInv, lmat);
  78500. }
  78501. else {
  78502. lmat.multiplyToRef(rmat, lmat);
  78503. }
  78504. }
  78505. lmat.m[12] = lx;
  78506. lmat.m[13] = ly;
  78507. lmat.m[14] = lz;
  78508. this.computeAbsoluteTransforms();
  78509. this._markAsDirtyAndDecompose();
  78510. };
  78511. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78512. var scaleMatrix = Bone._tmpMats[2];
  78513. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78514. if (mesh) {
  78515. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78516. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78517. }
  78518. rotMatInv.invert();
  78519. if (isNaN(rotMatInv.m[0])) {
  78520. // Matrix failed to invert.
  78521. // This can happen if scale is zero for example.
  78522. return false;
  78523. }
  78524. scaleMatrix.m[0] *= this._scalingDeterminant;
  78525. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78526. return true;
  78527. };
  78528. /**
  78529. * Get the position of the bone in local or world space
  78530. * @param space The space that the returned position is in
  78531. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78532. * @returns The position of the bone
  78533. */
  78534. Bone.prototype.getPosition = function (space, mesh) {
  78535. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78536. if (mesh === void 0) { mesh = null; }
  78537. var pos = BABYLON.Vector3.Zero();
  78538. this.getPositionToRef(space, mesh, pos);
  78539. return pos;
  78540. };
  78541. /**
  78542. * Copy the position of the bone to a vector3 in local or world space
  78543. * @param space The space that the returned position is in
  78544. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78545. * @param result The vector3 to copy the position to
  78546. */
  78547. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78548. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78549. if (space == BABYLON.Space.LOCAL) {
  78550. var lm = this.getLocalMatrix();
  78551. result.x = lm.m[12];
  78552. result.y = lm.m[13];
  78553. result.z = lm.m[14];
  78554. }
  78555. else {
  78556. var wm = null;
  78557. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78558. if (mesh) {
  78559. wm = mesh.getWorldMatrix();
  78560. }
  78561. this._skeleton.computeAbsoluteTransforms();
  78562. var tmat = Bone._tmpMats[0];
  78563. if (mesh && wm) {
  78564. tmat.copyFrom(this.getAbsoluteTransform());
  78565. tmat.multiplyToRef(wm, tmat);
  78566. }
  78567. else {
  78568. tmat = this.getAbsoluteTransform();
  78569. }
  78570. result.x = tmat.m[12];
  78571. result.y = tmat.m[13];
  78572. result.z = tmat.m[14];
  78573. }
  78574. };
  78575. /**
  78576. * Get the absolute position of the bone (world space)
  78577. * @param mesh The mesh that this bone is attached to
  78578. * @returns The absolute position of the bone
  78579. */
  78580. Bone.prototype.getAbsolutePosition = function (mesh) {
  78581. if (mesh === void 0) { mesh = null; }
  78582. var pos = BABYLON.Vector3.Zero();
  78583. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78584. return pos;
  78585. };
  78586. /**
  78587. * Copy the absolute position of the bone (world space) to the result param
  78588. * @param mesh The mesh that this bone is attached to
  78589. * @param result The vector3 to copy the absolute position to
  78590. */
  78591. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78592. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78593. };
  78594. /**
  78595. * Compute the absolute transforms of this bone and its children
  78596. */
  78597. Bone.prototype.computeAbsoluteTransforms = function () {
  78598. this._compose();
  78599. if (this._parent) {
  78600. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78601. }
  78602. else {
  78603. this._absoluteTransform.copyFrom(this._localMatrix);
  78604. var poseMatrix = this._skeleton.getPoseMatrix();
  78605. if (poseMatrix) {
  78606. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78607. }
  78608. }
  78609. var children = this.children;
  78610. var len = children.length;
  78611. for (var i = 0; i < len; i++) {
  78612. children[i].computeAbsoluteTransforms();
  78613. }
  78614. };
  78615. /**
  78616. * Get the world direction from an axis that is in the local space of the bone
  78617. * @param localAxis The local direction that is used to compute the world direction
  78618. * @param mesh The mesh that this bone is attached to
  78619. * @returns The world direction
  78620. */
  78621. Bone.prototype.getDirection = function (localAxis, mesh) {
  78622. if (mesh === void 0) { mesh = null; }
  78623. var result = BABYLON.Vector3.Zero();
  78624. this.getDirectionToRef(localAxis, mesh, result);
  78625. return result;
  78626. };
  78627. /**
  78628. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78629. * @param localAxis The local direction that is used to compute the world direction
  78630. * @param mesh The mesh that this bone is attached to
  78631. * @param result The vector3 that the world direction will be copied to
  78632. */
  78633. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78634. if (mesh === void 0) { mesh = null; }
  78635. var wm = null;
  78636. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78637. if (mesh) {
  78638. wm = mesh.getWorldMatrix();
  78639. }
  78640. this._skeleton.computeAbsoluteTransforms();
  78641. var mat = Bone._tmpMats[0];
  78642. mat.copyFrom(this.getAbsoluteTransform());
  78643. if (mesh && wm) {
  78644. mat.multiplyToRef(wm, mat);
  78645. }
  78646. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78647. result.normalize();
  78648. };
  78649. /**
  78650. * Get the euler rotation of the bone in local or world space
  78651. * @param space The space that the rotation should be in
  78652. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78653. * @returns The euler rotation
  78654. */
  78655. Bone.prototype.getRotation = function (space, mesh) {
  78656. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78657. if (mesh === void 0) { mesh = null; }
  78658. var result = BABYLON.Vector3.Zero();
  78659. this.getRotationToRef(space, mesh, result);
  78660. return result;
  78661. };
  78662. /**
  78663. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78664. * @param space The space that the rotation should be in
  78665. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78666. * @param result The vector3 that the rotation should be copied to
  78667. */
  78668. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78669. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78670. if (mesh === void 0) { mesh = null; }
  78671. var quat = Bone._tmpQuat;
  78672. this.getRotationQuaternionToRef(space, mesh, quat);
  78673. quat.toEulerAnglesToRef(result);
  78674. };
  78675. /**
  78676. * Get the quaternion rotation of the bone in either local or world space
  78677. * @param space The space that the rotation should be in
  78678. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78679. * @returns The quaternion rotation
  78680. */
  78681. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78682. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78683. if (mesh === void 0) { mesh = null; }
  78684. var result = BABYLON.Quaternion.Identity();
  78685. this.getRotationQuaternionToRef(space, mesh, result);
  78686. return result;
  78687. };
  78688. /**
  78689. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78690. * @param space The space that the rotation should be in
  78691. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78692. * @param result The quaternion that the rotation should be copied to
  78693. */
  78694. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78695. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78696. if (mesh === void 0) { mesh = null; }
  78697. if (space == BABYLON.Space.LOCAL) {
  78698. this._decompose();
  78699. result.copyFrom(this._localRotation);
  78700. }
  78701. else {
  78702. var mat = Bone._tmpMats[0];
  78703. var amat = this.getAbsoluteTransform();
  78704. if (mesh) {
  78705. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78706. }
  78707. else {
  78708. mat.copyFrom(amat);
  78709. }
  78710. mat.m[0] *= this._scalingDeterminant;
  78711. mat.m[1] *= this._scalingDeterminant;
  78712. mat.m[2] *= this._scalingDeterminant;
  78713. mat.decompose(undefined, result, undefined);
  78714. }
  78715. };
  78716. /**
  78717. * Get the rotation matrix of the bone in local or world space
  78718. * @param space The space that the rotation should be in
  78719. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78720. * @returns The rotation matrix
  78721. */
  78722. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78723. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78724. var result = BABYLON.Matrix.Identity();
  78725. this.getRotationMatrixToRef(space, mesh, result);
  78726. return result;
  78727. };
  78728. /**
  78729. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78730. * @param space The space that the rotation should be in
  78731. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78732. * @param result The quaternion that the rotation should be copied to
  78733. */
  78734. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78735. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78736. if (space == BABYLON.Space.LOCAL) {
  78737. this.getLocalMatrix().getRotationMatrixToRef(result);
  78738. }
  78739. else {
  78740. var mat = Bone._tmpMats[0];
  78741. var amat = this.getAbsoluteTransform();
  78742. if (mesh) {
  78743. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78744. }
  78745. else {
  78746. mat.copyFrom(amat);
  78747. }
  78748. mat.m[0] *= this._scalingDeterminant;
  78749. mat.m[1] *= this._scalingDeterminant;
  78750. mat.m[2] *= this._scalingDeterminant;
  78751. mat.getRotationMatrixToRef(result);
  78752. }
  78753. };
  78754. /**
  78755. * Get the world position of a point that is in the local space of the bone
  78756. * @param position The local position
  78757. * @param mesh The mesh that this bone is attached to
  78758. * @returns The world position
  78759. */
  78760. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78761. if (mesh === void 0) { mesh = null; }
  78762. var result = BABYLON.Vector3.Zero();
  78763. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78764. return result;
  78765. };
  78766. /**
  78767. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78768. * @param position The local position
  78769. * @param mesh The mesh that this bone is attached to
  78770. * @param result The vector3 that the world position should be copied to
  78771. */
  78772. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78773. if (mesh === void 0) { mesh = null; }
  78774. var wm = null;
  78775. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78776. if (mesh) {
  78777. wm = mesh.getWorldMatrix();
  78778. }
  78779. this._skeleton.computeAbsoluteTransforms();
  78780. var tmat = Bone._tmpMats[0];
  78781. if (mesh && wm) {
  78782. tmat.copyFrom(this.getAbsoluteTransform());
  78783. tmat.multiplyToRef(wm, tmat);
  78784. }
  78785. else {
  78786. tmat = this.getAbsoluteTransform();
  78787. }
  78788. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78789. };
  78790. /**
  78791. * Get the local position of a point that is in world space
  78792. * @param position The world position
  78793. * @param mesh The mesh that this bone is attached to
  78794. * @returns The local position
  78795. */
  78796. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78797. if (mesh === void 0) { mesh = null; }
  78798. var result = BABYLON.Vector3.Zero();
  78799. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78800. return result;
  78801. };
  78802. /**
  78803. * Get the local position of a point that is in world space and copy it to the result param
  78804. * @param position The world position
  78805. * @param mesh The mesh that this bone is attached to
  78806. * @param result The vector3 that the local position should be copied to
  78807. */
  78808. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78809. if (mesh === void 0) { mesh = null; }
  78810. var wm = null;
  78811. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78812. if (mesh) {
  78813. wm = mesh.getWorldMatrix();
  78814. }
  78815. this._skeleton.computeAbsoluteTransforms();
  78816. var tmat = Bone._tmpMats[0];
  78817. tmat.copyFrom(this.getAbsoluteTransform());
  78818. if (mesh && wm) {
  78819. tmat.multiplyToRef(wm, tmat);
  78820. }
  78821. tmat.invert();
  78822. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78823. };
  78824. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78825. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78826. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78827. return Bone;
  78828. }(BABYLON.Node));
  78829. BABYLON.Bone = Bone;
  78830. })(BABYLON || (BABYLON = {}));
  78831. //# sourceMappingURL=babylon.bone.js.map
  78832. var BABYLON;
  78833. (function (BABYLON) {
  78834. /**
  78835. * Class used to apply inverse kinematics to bones
  78836. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78837. */
  78838. var BoneIKController = /** @class */ (function () {
  78839. /**
  78840. * Creates a new BoneIKController
  78841. * @param mesh defines the mesh to control
  78842. * @param bone defines the bone to control
  78843. * @param options defines options to set up the controller
  78844. */
  78845. function BoneIKController(mesh, bone, options) {
  78846. /**
  78847. * Gets or sets the target position
  78848. */
  78849. this.targetPosition = BABYLON.Vector3.Zero();
  78850. /**
  78851. * Gets or sets the pole target position
  78852. */
  78853. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78854. /**
  78855. * Gets or sets the pole target local offset
  78856. */
  78857. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78858. /**
  78859. * Gets or sets the pole angle
  78860. */
  78861. this.poleAngle = 0;
  78862. /**
  78863. * 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)
  78864. */
  78865. this.slerpAmount = 1;
  78866. this._bone1Quat = BABYLON.Quaternion.Identity();
  78867. this._bone1Mat = BABYLON.Matrix.Identity();
  78868. this._bone2Ang = Math.PI;
  78869. this._maxAngle = Math.PI;
  78870. this._rightHandedSystem = false;
  78871. this._bendAxis = BABYLON.Vector3.Right();
  78872. this._slerping = false;
  78873. this._adjustRoll = 0;
  78874. this._bone2 = bone;
  78875. this._bone1 = bone.getParent();
  78876. if (!this._bone1) {
  78877. return;
  78878. }
  78879. this.mesh = mesh;
  78880. var bonePos = bone.getPosition();
  78881. if (bone.getAbsoluteTransform().determinant() > 0) {
  78882. this._rightHandedSystem = true;
  78883. this._bendAxis.x = 0;
  78884. this._bendAxis.y = 0;
  78885. this._bendAxis.z = -1;
  78886. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78887. this._adjustRoll = Math.PI * .5;
  78888. this._bendAxis.z = 1;
  78889. }
  78890. }
  78891. if (this._bone1.length) {
  78892. var boneScale1 = this._bone1.getScale();
  78893. var boneScale2 = this._bone2.getScale();
  78894. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78895. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78896. }
  78897. else if (this._bone1.children[0]) {
  78898. mesh.computeWorldMatrix(true);
  78899. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78900. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78901. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78902. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78903. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78904. }
  78905. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78906. this.maxAngle = Math.PI;
  78907. if (options) {
  78908. if (options.targetMesh) {
  78909. this.targetMesh = options.targetMesh;
  78910. this.targetMesh.computeWorldMatrix(true);
  78911. }
  78912. if (options.poleTargetMesh) {
  78913. this.poleTargetMesh = options.poleTargetMesh;
  78914. this.poleTargetMesh.computeWorldMatrix(true);
  78915. }
  78916. else if (options.poleTargetBone) {
  78917. this.poleTargetBone = options.poleTargetBone;
  78918. }
  78919. else if (this._bone1.getParent()) {
  78920. this.poleTargetBone = this._bone1.getParent();
  78921. }
  78922. if (options.poleTargetLocalOffset) {
  78923. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78924. }
  78925. if (options.poleAngle) {
  78926. this.poleAngle = options.poleAngle;
  78927. }
  78928. if (options.bendAxis) {
  78929. this._bendAxis.copyFrom(options.bendAxis);
  78930. }
  78931. if (options.maxAngle) {
  78932. this.maxAngle = options.maxAngle;
  78933. }
  78934. if (options.slerpAmount) {
  78935. this.slerpAmount = options.slerpAmount;
  78936. }
  78937. }
  78938. }
  78939. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78940. /**
  78941. * Gets or sets maximum allowed angle
  78942. */
  78943. get: function () {
  78944. return this._maxAngle;
  78945. },
  78946. set: function (value) {
  78947. this._setMaxAngle(value);
  78948. },
  78949. enumerable: true,
  78950. configurable: true
  78951. });
  78952. BoneIKController.prototype._setMaxAngle = function (ang) {
  78953. if (ang < 0) {
  78954. ang = 0;
  78955. }
  78956. if (ang > Math.PI || ang == undefined) {
  78957. ang = Math.PI;
  78958. }
  78959. this._maxAngle = ang;
  78960. var a = this._bone1Length;
  78961. var b = this._bone2Length;
  78962. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78963. };
  78964. /**
  78965. * Force the controller to update the bones
  78966. */
  78967. BoneIKController.prototype.update = function () {
  78968. var bone1 = this._bone1;
  78969. if (!bone1) {
  78970. return;
  78971. }
  78972. var target = this.targetPosition;
  78973. var poleTarget = this.poleTargetPosition;
  78974. var mat1 = BoneIKController._tmpMats[0];
  78975. var mat2 = BoneIKController._tmpMats[1];
  78976. if (this.targetMesh) {
  78977. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78978. }
  78979. if (this.poleTargetBone) {
  78980. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78981. }
  78982. else if (this.poleTargetMesh) {
  78983. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78984. }
  78985. var bonePos = BoneIKController._tmpVecs[0];
  78986. var zaxis = BoneIKController._tmpVecs[1];
  78987. var xaxis = BoneIKController._tmpVecs[2];
  78988. var yaxis = BoneIKController._tmpVecs[3];
  78989. var upAxis = BoneIKController._tmpVecs[4];
  78990. var _tmpQuat = BoneIKController._tmpQuat;
  78991. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78992. poleTarget.subtractToRef(bonePos, upAxis);
  78993. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78994. upAxis.y = 1;
  78995. }
  78996. else {
  78997. upAxis.normalize();
  78998. }
  78999. target.subtractToRef(bonePos, yaxis);
  79000. yaxis.normalize();
  79001. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79002. zaxis.normalize();
  79003. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79004. xaxis.normalize();
  79005. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79006. var a = this._bone1Length;
  79007. var b = this._bone2Length;
  79008. var c = BABYLON.Vector3.Distance(bonePos, target);
  79009. if (this._maxReach > 0) {
  79010. c = Math.min(this._maxReach, c);
  79011. }
  79012. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79013. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79014. if (acosa > 1) {
  79015. acosa = 1;
  79016. }
  79017. if (acosb > 1) {
  79018. acosb = 1;
  79019. }
  79020. if (acosa < -1) {
  79021. acosa = -1;
  79022. }
  79023. if (acosb < -1) {
  79024. acosb = -1;
  79025. }
  79026. var angA = Math.acos(acosa);
  79027. var angB = Math.acos(acosb);
  79028. var angC = -angA - angB;
  79029. if (this._rightHandedSystem) {
  79030. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79031. mat2.multiplyToRef(mat1, mat1);
  79032. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79033. mat2.multiplyToRef(mat1, mat1);
  79034. }
  79035. else {
  79036. var _tmpVec = BoneIKController._tmpVecs[5];
  79037. _tmpVec.copyFrom(this._bendAxis);
  79038. _tmpVec.x *= -1;
  79039. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79040. mat2.multiplyToRef(mat1, mat1);
  79041. }
  79042. if (this.poleAngle) {
  79043. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79044. mat1.multiplyToRef(mat2, mat1);
  79045. }
  79046. if (this._bone1) {
  79047. if (this.slerpAmount < 1) {
  79048. if (!this._slerping) {
  79049. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79050. }
  79051. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79052. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79053. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79054. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79055. this._slerping = true;
  79056. }
  79057. else {
  79058. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79059. this._bone1Mat.copyFrom(mat1);
  79060. this._slerping = false;
  79061. }
  79062. }
  79063. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79064. this._bone2Ang = angC;
  79065. };
  79066. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79067. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79068. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79069. return BoneIKController;
  79070. }());
  79071. BABYLON.BoneIKController = BoneIKController;
  79072. })(BABYLON || (BABYLON = {}));
  79073. //# sourceMappingURL=babylon.boneIKController.js.map
  79074. var BABYLON;
  79075. (function (BABYLON) {
  79076. /**
  79077. * Class used to make a bone look toward a point in space
  79078. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79079. */
  79080. var BoneLookController = /** @class */ (function () {
  79081. /**
  79082. * Create a BoneLookController
  79083. * @param mesh the mesh that the bone belongs to
  79084. * @param bone the bone that will be looking to the target
  79085. * @param target the target Vector3 to look at
  79086. * @param settings optional settings:
  79087. * * maxYaw: the maximum angle the bone will yaw to
  79088. * * minYaw: the minimum angle the bone will yaw to
  79089. * * maxPitch: the maximum angle the bone will pitch to
  79090. * * minPitch: the minimum angle the bone will yaw to
  79091. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79092. * * upAxis: the up axis of the coordinate system
  79093. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79094. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79095. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79096. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79097. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79098. * * adjustRoll: used to make an adjustment to the roll of the bone
  79099. **/
  79100. function BoneLookController(mesh, bone, target, options) {
  79101. /**
  79102. * The up axis of the coordinate system that is used when the bone is rotated
  79103. */
  79104. this.upAxis = BABYLON.Vector3.Up();
  79105. /**
  79106. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79107. */
  79108. this.upAxisSpace = BABYLON.Space.LOCAL;
  79109. /**
  79110. * Used to make an adjustment to the yaw of the bone
  79111. */
  79112. this.adjustYaw = 0;
  79113. /**
  79114. * Used to make an adjustment to the pitch of the bone
  79115. */
  79116. this.adjustPitch = 0;
  79117. /**
  79118. * Used to make an adjustment to the roll of the bone
  79119. */
  79120. this.adjustRoll = 0;
  79121. /**
  79122. * 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)
  79123. */
  79124. this.slerpAmount = 1;
  79125. this._boneQuat = BABYLON.Quaternion.Identity();
  79126. this._slerping = false;
  79127. this._firstFrameSkipped = false;
  79128. this._fowardAxis = BABYLON.Vector3.Forward();
  79129. this.mesh = mesh;
  79130. this.bone = bone;
  79131. this.target = target;
  79132. if (options) {
  79133. if (options.adjustYaw) {
  79134. this.adjustYaw = options.adjustYaw;
  79135. }
  79136. if (options.adjustPitch) {
  79137. this.adjustPitch = options.adjustPitch;
  79138. }
  79139. if (options.adjustRoll) {
  79140. this.adjustRoll = options.adjustRoll;
  79141. }
  79142. if (options.maxYaw != null) {
  79143. this.maxYaw = options.maxYaw;
  79144. }
  79145. else {
  79146. this.maxYaw = Math.PI;
  79147. }
  79148. if (options.minYaw != null) {
  79149. this.minYaw = options.minYaw;
  79150. }
  79151. else {
  79152. this.minYaw = -Math.PI;
  79153. }
  79154. if (options.maxPitch != null) {
  79155. this.maxPitch = options.maxPitch;
  79156. }
  79157. else {
  79158. this.maxPitch = Math.PI;
  79159. }
  79160. if (options.minPitch != null) {
  79161. this.minPitch = options.minPitch;
  79162. }
  79163. else {
  79164. this.minPitch = -Math.PI;
  79165. }
  79166. if (options.slerpAmount != null) {
  79167. this.slerpAmount = options.slerpAmount;
  79168. }
  79169. if (options.upAxis != null) {
  79170. this.upAxis = options.upAxis;
  79171. }
  79172. if (options.upAxisSpace != null) {
  79173. this.upAxisSpace = options.upAxisSpace;
  79174. }
  79175. if (options.yawAxis != null || options.pitchAxis != null) {
  79176. var newYawAxis = BABYLON.Axis.Y;
  79177. var newPitchAxis = BABYLON.Axis.X;
  79178. if (options.yawAxis != null) {
  79179. newYawAxis = options.yawAxis.clone();
  79180. newYawAxis.normalize();
  79181. }
  79182. if (options.pitchAxis != null) {
  79183. newPitchAxis = options.pitchAxis.clone();
  79184. newPitchAxis.normalize();
  79185. }
  79186. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79187. this._transformYawPitch = BABYLON.Matrix.Identity();
  79188. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79189. this._transformYawPitchInv = this._transformYawPitch.clone();
  79190. this._transformYawPitch.invert();
  79191. }
  79192. }
  79193. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79194. this.upAxisSpace = BABYLON.Space.LOCAL;
  79195. }
  79196. }
  79197. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79198. /**
  79199. * Gets or sets the minimum yaw angle that the bone can look to
  79200. */
  79201. get: function () {
  79202. return this._minYaw;
  79203. },
  79204. set: function (value) {
  79205. this._minYaw = value;
  79206. this._minYawSin = Math.sin(value);
  79207. this._minYawCos = Math.cos(value);
  79208. if (this._maxYaw != null) {
  79209. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79210. this._yawRange = this._maxYaw - this._minYaw;
  79211. }
  79212. },
  79213. enumerable: true,
  79214. configurable: true
  79215. });
  79216. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79217. /**
  79218. * Gets or sets the maximum yaw angle that the bone can look to
  79219. */
  79220. get: function () {
  79221. return this._maxYaw;
  79222. },
  79223. set: function (value) {
  79224. this._maxYaw = value;
  79225. this._maxYawSin = Math.sin(value);
  79226. this._maxYawCos = Math.cos(value);
  79227. if (this._minYaw != null) {
  79228. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79229. this._yawRange = this._maxYaw - this._minYaw;
  79230. }
  79231. },
  79232. enumerable: true,
  79233. configurable: true
  79234. });
  79235. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79236. /**
  79237. * Gets or sets the minimum pitch angle that the bone can look to
  79238. */
  79239. get: function () {
  79240. return this._minPitch;
  79241. },
  79242. set: function (value) {
  79243. this._minPitch = value;
  79244. this._minPitchTan = Math.tan(value);
  79245. },
  79246. enumerable: true,
  79247. configurable: true
  79248. });
  79249. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79250. /**
  79251. * Gets or sets the maximum pitch angle that the bone can look to
  79252. */
  79253. get: function () {
  79254. return this._maxPitch;
  79255. },
  79256. set: function (value) {
  79257. this._maxPitch = value;
  79258. this._maxPitchTan = Math.tan(value);
  79259. },
  79260. enumerable: true,
  79261. configurable: true
  79262. });
  79263. /**
  79264. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79265. */
  79266. BoneLookController.prototype.update = function () {
  79267. //skip the first frame when slerping so that the mesh rotation is correct
  79268. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79269. this._firstFrameSkipped = true;
  79270. return;
  79271. }
  79272. var bone = this.bone;
  79273. var bonePos = BoneLookController._tmpVecs[0];
  79274. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79275. var target = this.target;
  79276. var _tmpMat1 = BoneLookController._tmpMats[0];
  79277. var _tmpMat2 = BoneLookController._tmpMats[1];
  79278. var mesh = this.mesh;
  79279. var parentBone = bone.getParent();
  79280. var upAxis = BoneLookController._tmpVecs[1];
  79281. upAxis.copyFrom(this.upAxis);
  79282. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79283. if (this._transformYawPitch) {
  79284. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79285. }
  79286. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79287. }
  79288. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79289. mesh.getDirectionToRef(upAxis, upAxis);
  79290. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79291. upAxis.normalize();
  79292. }
  79293. }
  79294. var checkYaw = false;
  79295. var checkPitch = false;
  79296. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79297. checkYaw = true;
  79298. }
  79299. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79300. checkPitch = true;
  79301. }
  79302. if (checkYaw || checkPitch) {
  79303. var spaceMat = BoneLookController._tmpMats[2];
  79304. var spaceMatInv = BoneLookController._tmpMats[3];
  79305. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79306. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79307. }
  79308. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79309. spaceMat.copyFrom(mesh.getWorldMatrix());
  79310. }
  79311. else {
  79312. var forwardAxis = BoneLookController._tmpVecs[2];
  79313. forwardAxis.copyFrom(this._fowardAxis);
  79314. if (this._transformYawPitch) {
  79315. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79316. }
  79317. if (parentBone) {
  79318. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79319. }
  79320. else {
  79321. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79322. }
  79323. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79324. rightAxis.normalize();
  79325. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79326. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79327. }
  79328. spaceMat.invertToRef(spaceMatInv);
  79329. var xzlen = null;
  79330. if (checkPitch) {
  79331. var localTarget = BoneLookController._tmpVecs[3];
  79332. target.subtractToRef(bonePos, localTarget);
  79333. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79334. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79335. var pitch = Math.atan2(localTarget.y, xzlen);
  79336. var newPitch = pitch;
  79337. if (pitch > this._maxPitch) {
  79338. localTarget.y = this._maxPitchTan * xzlen;
  79339. newPitch = this._maxPitch;
  79340. }
  79341. else if (pitch < this._minPitch) {
  79342. localTarget.y = this._minPitchTan * xzlen;
  79343. newPitch = this._minPitch;
  79344. }
  79345. if (pitch != newPitch) {
  79346. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79347. localTarget.addInPlace(bonePos);
  79348. target = localTarget;
  79349. }
  79350. }
  79351. if (checkYaw) {
  79352. var localTarget = BoneLookController._tmpVecs[4];
  79353. target.subtractToRef(bonePos, localTarget);
  79354. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79355. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79356. var newYaw = yaw;
  79357. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79358. if (xzlen == null) {
  79359. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79360. }
  79361. if (this._yawRange > Math.PI) {
  79362. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79363. localTarget.z = this._maxYawCos * xzlen;
  79364. localTarget.x = this._maxYawSin * xzlen;
  79365. newYaw = this._maxYaw;
  79366. }
  79367. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79368. localTarget.z = this._minYawCos * xzlen;
  79369. localTarget.x = this._minYawSin * xzlen;
  79370. newYaw = this._minYaw;
  79371. }
  79372. }
  79373. else {
  79374. if (yaw > this._maxYaw) {
  79375. localTarget.z = this._maxYawCos * xzlen;
  79376. localTarget.x = this._maxYawSin * xzlen;
  79377. newYaw = this._maxYaw;
  79378. }
  79379. else if (yaw < this._minYaw) {
  79380. localTarget.z = this._minYawCos * xzlen;
  79381. localTarget.x = this._minYawSin * xzlen;
  79382. newYaw = this._minYaw;
  79383. }
  79384. }
  79385. }
  79386. if (this._slerping && this._yawRange > Math.PI) {
  79387. //are we going to be crossing into the min/max region?
  79388. var boneFwd = BoneLookController._tmpVecs[8];
  79389. boneFwd.copyFrom(BABYLON.Axis.Z);
  79390. if (this._transformYawPitch) {
  79391. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79392. }
  79393. var boneRotMat = BoneLookController._tmpMats[4];
  79394. this._boneQuat.toRotationMatrix(boneRotMat);
  79395. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79396. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79397. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79398. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79399. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79400. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79401. if (angBtwTar > angBtwMidYaw) {
  79402. if (xzlen == null) {
  79403. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79404. }
  79405. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79406. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79407. if (angBtwMin < angBtwMax) {
  79408. newYaw = boneYaw + Math.PI * .75;
  79409. localTarget.z = Math.cos(newYaw) * xzlen;
  79410. localTarget.x = Math.sin(newYaw) * xzlen;
  79411. }
  79412. else {
  79413. newYaw = boneYaw - Math.PI * .75;
  79414. localTarget.z = Math.cos(newYaw) * xzlen;
  79415. localTarget.x = Math.sin(newYaw) * xzlen;
  79416. }
  79417. }
  79418. }
  79419. if (yaw != newYaw) {
  79420. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79421. localTarget.addInPlace(bonePos);
  79422. target = localTarget;
  79423. }
  79424. }
  79425. }
  79426. var zaxis = BoneLookController._tmpVecs[5];
  79427. var xaxis = BoneLookController._tmpVecs[6];
  79428. var yaxis = BoneLookController._tmpVecs[7];
  79429. var _tmpQuat = BoneLookController._tmpQuat;
  79430. target.subtractToRef(bonePos, zaxis);
  79431. zaxis.normalize();
  79432. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79433. xaxis.normalize();
  79434. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79435. yaxis.normalize();
  79436. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79437. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79438. return;
  79439. }
  79440. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79441. return;
  79442. }
  79443. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79444. return;
  79445. }
  79446. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79447. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79448. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79449. }
  79450. if (this.slerpAmount < 1) {
  79451. if (!this._slerping) {
  79452. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79453. }
  79454. if (this._transformYawPitch) {
  79455. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79456. }
  79457. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79458. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79459. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79460. this._slerping = true;
  79461. }
  79462. else {
  79463. if (this._transformYawPitch) {
  79464. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79465. }
  79466. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79467. this._slerping = false;
  79468. }
  79469. };
  79470. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79471. var angDiff = ang2 - ang1;
  79472. angDiff %= Math.PI * 2;
  79473. if (angDiff > Math.PI) {
  79474. angDiff -= Math.PI * 2;
  79475. }
  79476. else if (angDiff < -Math.PI) {
  79477. angDiff += Math.PI * 2;
  79478. }
  79479. return angDiff;
  79480. };
  79481. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79482. ang1 %= (2 * Math.PI);
  79483. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79484. ang2 %= (2 * Math.PI);
  79485. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79486. var ab = 0;
  79487. if (ang1 < ang2) {
  79488. ab = ang2 - ang1;
  79489. }
  79490. else {
  79491. ab = ang1 - ang2;
  79492. }
  79493. if (ab > Math.PI) {
  79494. ab = Math.PI * 2 - ab;
  79495. }
  79496. return ab;
  79497. };
  79498. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79499. ang %= (2 * Math.PI);
  79500. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79501. ang1 %= (2 * Math.PI);
  79502. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79503. ang2 %= (2 * Math.PI);
  79504. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79505. if (ang1 < ang2) {
  79506. if (ang > ang1 && ang < ang2) {
  79507. return true;
  79508. }
  79509. }
  79510. else {
  79511. if (ang > ang2 && ang < ang1) {
  79512. return true;
  79513. }
  79514. }
  79515. return false;
  79516. };
  79517. 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()];
  79518. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79519. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79520. return BoneLookController;
  79521. }());
  79522. BABYLON.BoneLookController = BoneLookController;
  79523. })(BABYLON || (BABYLON = {}));
  79524. //# sourceMappingURL=babylon.boneLookController.js.map
  79525. var BABYLON;
  79526. (function (BABYLON) {
  79527. /**
  79528. * Class used to handle skinning animations
  79529. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79530. */
  79531. var Skeleton = /** @class */ (function () {
  79532. /**
  79533. * Creates a new skeleton
  79534. * @param name defines the skeleton name
  79535. * @param id defines the skeleton Id
  79536. * @param scene defines the hosting scene
  79537. */
  79538. function Skeleton(
  79539. /** defines the skeleton name */
  79540. name,
  79541. /** defines the skeleton Id */
  79542. id, scene) {
  79543. this.name = name;
  79544. this.id = id;
  79545. /**
  79546. * Gets the list of child bones
  79547. */
  79548. this.bones = new Array();
  79549. /**
  79550. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79551. */
  79552. this.needInitialSkinMatrix = false;
  79553. this._isDirty = true;
  79554. this._meshesWithPoseMatrix = new Array();
  79555. this._identity = BABYLON.Matrix.Identity();
  79556. this._ranges = {};
  79557. this._lastAbsoluteTransformsUpdateId = -1;
  79558. /**
  79559. * Specifies if the skeleton should be serialized
  79560. */
  79561. this.doNotSerialize = false;
  79562. this._animationPropertiesOverride = null;
  79563. // Events
  79564. /**
  79565. * An observable triggered before computing the skeleton's matrices
  79566. */
  79567. this.onBeforeComputeObservable = new BABYLON.Observable();
  79568. this.bones = [];
  79569. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79570. scene.skeletons.push(this);
  79571. //make sure it will recalculate the matrix next time prepare is called.
  79572. this._isDirty = true;
  79573. }
  79574. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79575. /**
  79576. * Gets or sets the animation properties override
  79577. */
  79578. get: function () {
  79579. if (!this._animationPropertiesOverride) {
  79580. return this._scene.animationPropertiesOverride;
  79581. }
  79582. return this._animationPropertiesOverride;
  79583. },
  79584. set: function (value) {
  79585. this._animationPropertiesOverride = value;
  79586. },
  79587. enumerable: true,
  79588. configurable: true
  79589. });
  79590. // Members
  79591. /**
  79592. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79593. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79594. * @returns a Float32Array containing matrices data
  79595. */
  79596. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79597. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79598. return mesh._bonesTransformMatrices;
  79599. }
  79600. if (!this._transformMatrices) {
  79601. this.prepare();
  79602. }
  79603. return this._transformMatrices;
  79604. };
  79605. /**
  79606. * Gets the current hosting scene
  79607. * @returns a scene object
  79608. */
  79609. Skeleton.prototype.getScene = function () {
  79610. return this._scene;
  79611. };
  79612. // Methods
  79613. /**
  79614. * Gets a string representing the current skeleton data
  79615. * @param fullDetails defines a boolean indicating if we want a verbose version
  79616. * @returns a string representing the current skeleton data
  79617. */
  79618. Skeleton.prototype.toString = function (fullDetails) {
  79619. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79620. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79621. if (fullDetails) {
  79622. ret += ", Ranges: {";
  79623. var first = true;
  79624. for (var name_1 in this._ranges) {
  79625. if (first) {
  79626. ret += ", ";
  79627. first = false;
  79628. }
  79629. ret += name_1;
  79630. }
  79631. ret += "}";
  79632. }
  79633. return ret;
  79634. };
  79635. /**
  79636. * Get bone's index searching by name
  79637. * @param name defines bone's name to search for
  79638. * @return the indice of the bone. Returns -1 if not found
  79639. */
  79640. Skeleton.prototype.getBoneIndexByName = function (name) {
  79641. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79642. if (this.bones[boneIndex].name === name) {
  79643. return boneIndex;
  79644. }
  79645. }
  79646. return -1;
  79647. };
  79648. /**
  79649. * Creater a new animation range
  79650. * @param name defines the name of the range
  79651. * @param from defines the start key
  79652. * @param to defines the end key
  79653. */
  79654. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79655. // check name not already in use
  79656. if (!this._ranges[name]) {
  79657. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79658. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79659. if (this.bones[i].animations[0]) {
  79660. this.bones[i].animations[0].createRange(name, from, to);
  79661. }
  79662. }
  79663. }
  79664. };
  79665. /**
  79666. * Delete a specific animation range
  79667. * @param name defines the name of the range
  79668. * @param deleteFrames defines if frames must be removed as well
  79669. */
  79670. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79671. if (deleteFrames === void 0) { deleteFrames = true; }
  79672. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79673. if (this.bones[i].animations[0]) {
  79674. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79675. }
  79676. }
  79677. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79678. };
  79679. /**
  79680. * Gets a specific animation range
  79681. * @param name defines the name of the range to look for
  79682. * @returns the requested animation range or null if not found
  79683. */
  79684. Skeleton.prototype.getAnimationRange = function (name) {
  79685. return this._ranges[name];
  79686. };
  79687. /**
  79688. * Gets the list of all animation ranges defined on this skeleton
  79689. * @returns an array
  79690. */
  79691. Skeleton.prototype.getAnimationRanges = function () {
  79692. var animationRanges = [];
  79693. var name;
  79694. var i = 0;
  79695. for (name in this._ranges) {
  79696. animationRanges[i] = this._ranges[name];
  79697. i++;
  79698. }
  79699. return animationRanges;
  79700. };
  79701. /**
  79702. * Copy animation range from a source skeleton.
  79703. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79704. * @param source defines the source skeleton
  79705. * @param name defines the name of the range to copy
  79706. * @param rescaleAsRequired defines if rescaling must be applied if required
  79707. * @returns true if operation was successful
  79708. */
  79709. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79710. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79711. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79712. return false;
  79713. }
  79714. var ret = true;
  79715. var frameOffset = this._getHighestAnimationFrame() + 1;
  79716. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79717. var boneDict = {};
  79718. var sourceBones = source.bones;
  79719. var nBones;
  79720. var i;
  79721. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79722. boneDict[sourceBones[i].name] = sourceBones[i];
  79723. }
  79724. if (this.bones.length !== sourceBones.length) {
  79725. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79726. ret = false;
  79727. }
  79728. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79729. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79730. var boneName = this.bones[i].name;
  79731. var sourceBone = boneDict[boneName];
  79732. if (sourceBone) {
  79733. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79734. }
  79735. else {
  79736. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79737. ret = false;
  79738. }
  79739. }
  79740. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79741. var range = source.getAnimationRange(name);
  79742. if (range) {
  79743. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79744. }
  79745. return ret;
  79746. };
  79747. /**
  79748. * Forces the skeleton to go to rest pose
  79749. */
  79750. Skeleton.prototype.returnToRest = function () {
  79751. for (var index = 0; index < this.bones.length; index++) {
  79752. this.bones[index].returnToRest();
  79753. }
  79754. };
  79755. Skeleton.prototype._getHighestAnimationFrame = function () {
  79756. var ret = 0;
  79757. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79758. if (this.bones[i].animations[0]) {
  79759. var highest = this.bones[i].animations[0].getHighestFrame();
  79760. if (ret < highest) {
  79761. ret = highest;
  79762. }
  79763. }
  79764. }
  79765. return ret;
  79766. };
  79767. /**
  79768. * Begin a specific animation range
  79769. * @param name defines the name of the range to start
  79770. * @param loop defines if looping must be turned on (false by default)
  79771. * @param speedRatio defines the speed ratio to apply (1 by default)
  79772. * @param onAnimationEnd defines a callback which will be called when animation will end
  79773. * @returns a new animatable
  79774. */
  79775. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79776. var range = this.getAnimationRange(name);
  79777. if (!range) {
  79778. return null;
  79779. }
  79780. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79781. };
  79782. /** @hidden */
  79783. Skeleton.prototype._markAsDirty = function () {
  79784. this._isDirty = true;
  79785. };
  79786. /** @hidden */
  79787. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79788. this._meshesWithPoseMatrix.push(mesh);
  79789. };
  79790. /** @hidden */
  79791. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79792. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79793. if (index > -1) {
  79794. this._meshesWithPoseMatrix.splice(index, 1);
  79795. }
  79796. };
  79797. /** @hidden */
  79798. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79799. this.onBeforeComputeObservable.notifyObservers(this);
  79800. for (var index = 0; index < this.bones.length; index++) {
  79801. var bone = this.bones[index];
  79802. var parentBone = bone.getParent();
  79803. if (parentBone) {
  79804. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79805. }
  79806. else {
  79807. if (initialSkinMatrix) {
  79808. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79809. }
  79810. else {
  79811. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79812. }
  79813. }
  79814. if (bone._index !== -1) {
  79815. var mappedIndex = bone._index === null ? index : bone._index;
  79816. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79817. }
  79818. }
  79819. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79820. };
  79821. /**
  79822. * Build all resources required to render a skeleton
  79823. */
  79824. Skeleton.prototype.prepare = function () {
  79825. if (!this._isDirty) {
  79826. return;
  79827. }
  79828. if (this.needInitialSkinMatrix) {
  79829. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79830. var mesh = this._meshesWithPoseMatrix[index];
  79831. var poseMatrix = mesh.getPoseMatrix();
  79832. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79833. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79834. }
  79835. if (this._synchronizedWithMesh !== mesh) {
  79836. this._synchronizedWithMesh = mesh;
  79837. // Prepare bones
  79838. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79839. var bone = this.bones[boneIndex];
  79840. if (!bone.getParent()) {
  79841. var matrix = bone.getBaseMatrix();
  79842. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79843. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79844. }
  79845. }
  79846. }
  79847. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79848. }
  79849. }
  79850. else {
  79851. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79852. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79853. }
  79854. this._computeTransformMatrices(this._transformMatrices, null);
  79855. }
  79856. this._isDirty = false;
  79857. this._scene._activeBones.addCount(this.bones.length, false);
  79858. };
  79859. /**
  79860. * Gets the list of animatables currently running for this skeleton
  79861. * @returns an array of animatables
  79862. */
  79863. Skeleton.prototype.getAnimatables = function () {
  79864. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79865. this._animatables = [];
  79866. for (var index = 0; index < this.bones.length; index++) {
  79867. this._animatables.push(this.bones[index]);
  79868. }
  79869. }
  79870. return this._animatables;
  79871. };
  79872. /**
  79873. * Clone the current skeleton
  79874. * @param name defines the name of the new skeleton
  79875. * @param id defines the id of the enw skeleton
  79876. * @returns the new skeleton
  79877. */
  79878. Skeleton.prototype.clone = function (name, id) {
  79879. var result = new Skeleton(name, id || name, this._scene);
  79880. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79881. for (var index = 0; index < this.bones.length; index++) {
  79882. var source = this.bones[index];
  79883. var parentBone = null;
  79884. var parent_1 = source.getParent();
  79885. if (parent_1) {
  79886. var parentIndex = this.bones.indexOf(parent_1);
  79887. parentBone = result.bones[parentIndex];
  79888. }
  79889. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79890. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79891. }
  79892. if (this._ranges) {
  79893. result._ranges = {};
  79894. for (var rangeName in this._ranges) {
  79895. var range = this._ranges[rangeName];
  79896. if (range) {
  79897. result._ranges[rangeName] = range.clone();
  79898. }
  79899. }
  79900. }
  79901. this._isDirty = true;
  79902. return result;
  79903. };
  79904. /**
  79905. * Enable animation blending for this skeleton
  79906. * @param blendingSpeed defines the blending speed to apply
  79907. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79908. */
  79909. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79910. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79911. this.bones.forEach(function (bone) {
  79912. bone.animations.forEach(function (animation) {
  79913. animation.enableBlending = true;
  79914. animation.blendingSpeed = blendingSpeed;
  79915. });
  79916. });
  79917. };
  79918. /**
  79919. * Releases all resources associated with the current skeleton
  79920. */
  79921. Skeleton.prototype.dispose = function () {
  79922. this._meshesWithPoseMatrix = [];
  79923. // Animations
  79924. this.getScene().stopAnimation(this);
  79925. // Remove from scene
  79926. this.getScene().removeSkeleton(this);
  79927. };
  79928. /**
  79929. * Serialize the skeleton in a JSON object
  79930. * @returns a JSON object
  79931. */
  79932. Skeleton.prototype.serialize = function () {
  79933. var serializationObject = {};
  79934. serializationObject.name = this.name;
  79935. serializationObject.id = this.id;
  79936. if (this.dimensionsAtRest) {
  79937. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79938. }
  79939. serializationObject.bones = [];
  79940. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79941. for (var index = 0; index < this.bones.length; index++) {
  79942. var bone = this.bones[index];
  79943. var parent_2 = bone.getParent();
  79944. var serializedBone = {
  79945. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79946. name: bone.name,
  79947. matrix: bone.getBaseMatrix().toArray(),
  79948. rest: bone.getRestPose().toArray()
  79949. };
  79950. serializationObject.bones.push(serializedBone);
  79951. if (bone.length) {
  79952. serializedBone.length = bone.length;
  79953. }
  79954. if (bone.metadata) {
  79955. serializedBone.metadata = bone.metadata;
  79956. }
  79957. if (bone.animations && bone.animations.length > 0) {
  79958. serializedBone.animation = bone.animations[0].serialize();
  79959. }
  79960. serializationObject.ranges = [];
  79961. for (var name in this._ranges) {
  79962. var source = this._ranges[name];
  79963. if (!source) {
  79964. continue;
  79965. }
  79966. var range = {};
  79967. range.name = name;
  79968. range.from = source.from;
  79969. range.to = source.to;
  79970. serializationObject.ranges.push(range);
  79971. }
  79972. }
  79973. return serializationObject;
  79974. };
  79975. /**
  79976. * Creates a new skeleton from serialized data
  79977. * @param parsedSkeleton defines the serialized data
  79978. * @param scene defines the hosting scene
  79979. * @returns a new skeleton
  79980. */
  79981. Skeleton.Parse = function (parsedSkeleton, scene) {
  79982. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79983. if (parsedSkeleton.dimensionsAtRest) {
  79984. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79985. }
  79986. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79987. var index;
  79988. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79989. var parsedBone = parsedSkeleton.bones[index];
  79990. var parentBone = null;
  79991. if (parsedBone.parentBoneIndex > -1) {
  79992. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79993. }
  79994. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79995. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79996. if (parsedBone.length) {
  79997. bone.length = parsedBone.length;
  79998. }
  79999. if (parsedBone.metadata) {
  80000. bone.metadata = parsedBone.metadata;
  80001. }
  80002. if (parsedBone.animation) {
  80003. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80004. }
  80005. }
  80006. // placed after bones, so createAnimationRange can cascade down
  80007. if (parsedSkeleton.ranges) {
  80008. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80009. var data = parsedSkeleton.ranges[index];
  80010. skeleton.createAnimationRange(data.name, data.from, data.to);
  80011. }
  80012. }
  80013. return skeleton;
  80014. };
  80015. /**
  80016. * Compute all node absolute transforms
  80017. * @param forceUpdate defines if computation must be done even if cache is up to date
  80018. */
  80019. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80020. if (forceUpdate === void 0) { forceUpdate = false; }
  80021. var renderId = this._scene.getRenderId();
  80022. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80023. this.bones[0].computeAbsoluteTransforms();
  80024. this._lastAbsoluteTransformsUpdateId = renderId;
  80025. }
  80026. };
  80027. /**
  80028. * Gets the root pose matrix
  80029. * @returns a matrix
  80030. */
  80031. Skeleton.prototype.getPoseMatrix = function () {
  80032. var poseMatrix = null;
  80033. if (this._meshesWithPoseMatrix.length > 0) {
  80034. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80035. }
  80036. return poseMatrix;
  80037. };
  80038. /**
  80039. * Sorts bones per internal index
  80040. */
  80041. Skeleton.prototype.sortBones = function () {
  80042. var bones = new Array();
  80043. var visited = new Array(this.bones.length);
  80044. for (var index = 0; index < this.bones.length; index++) {
  80045. this._sortBones(index, bones, visited);
  80046. }
  80047. this.bones = bones;
  80048. };
  80049. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80050. if (visited[index]) {
  80051. return;
  80052. }
  80053. visited[index] = true;
  80054. var bone = this.bones[index];
  80055. if (bone._index === undefined) {
  80056. bone._index = index;
  80057. }
  80058. var parentBone = bone.getParent();
  80059. if (parentBone) {
  80060. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80061. }
  80062. bones.push(bone);
  80063. };
  80064. return Skeleton;
  80065. }());
  80066. BABYLON.Skeleton = Skeleton;
  80067. })(BABYLON || (BABYLON = {}));
  80068. //# sourceMappingURL=babylon.skeleton.js.map
  80069. var BABYLON;
  80070. (function (BABYLON) {
  80071. var SphericalPolynomial = /** @class */ (function () {
  80072. function SphericalPolynomial() {
  80073. this.x = BABYLON.Vector3.Zero();
  80074. this.y = BABYLON.Vector3.Zero();
  80075. this.z = BABYLON.Vector3.Zero();
  80076. this.xx = BABYLON.Vector3.Zero();
  80077. this.yy = BABYLON.Vector3.Zero();
  80078. this.zz = BABYLON.Vector3.Zero();
  80079. this.xy = BABYLON.Vector3.Zero();
  80080. this.yz = BABYLON.Vector3.Zero();
  80081. this.zx = BABYLON.Vector3.Zero();
  80082. }
  80083. SphericalPolynomial.prototype.addAmbient = function (color) {
  80084. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80085. this.xx = this.xx.add(colorVector);
  80086. this.yy = this.yy.add(colorVector);
  80087. this.zz = this.zz.add(colorVector);
  80088. };
  80089. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80090. var result = new SphericalPolynomial();
  80091. result.x = harmonics.L11.scale(1.02333);
  80092. result.y = harmonics.L1_1.scale(1.02333);
  80093. result.z = harmonics.L10.scale(1.02333);
  80094. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80095. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80096. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80097. result.yz = harmonics.L2_1.scale(0.858086);
  80098. result.zx = harmonics.L21.scale(0.858086);
  80099. result.xy = harmonics.L2_2.scale(0.858086);
  80100. result.scale(1.0 / Math.PI);
  80101. return result;
  80102. };
  80103. SphericalPolynomial.prototype.scale = function (scale) {
  80104. this.x = this.x.scale(scale);
  80105. this.y = this.y.scale(scale);
  80106. this.z = this.z.scale(scale);
  80107. this.xx = this.xx.scale(scale);
  80108. this.yy = this.yy.scale(scale);
  80109. this.zz = this.zz.scale(scale);
  80110. this.yz = this.yz.scale(scale);
  80111. this.zx = this.zx.scale(scale);
  80112. this.xy = this.xy.scale(scale);
  80113. };
  80114. return SphericalPolynomial;
  80115. }());
  80116. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80117. var SphericalHarmonics = /** @class */ (function () {
  80118. function SphericalHarmonics() {
  80119. this.L00 = BABYLON.Vector3.Zero();
  80120. this.L1_1 = BABYLON.Vector3.Zero();
  80121. this.L10 = BABYLON.Vector3.Zero();
  80122. this.L11 = BABYLON.Vector3.Zero();
  80123. this.L2_2 = BABYLON.Vector3.Zero();
  80124. this.L2_1 = BABYLON.Vector3.Zero();
  80125. this.L20 = BABYLON.Vector3.Zero();
  80126. this.L21 = BABYLON.Vector3.Zero();
  80127. this.L22 = BABYLON.Vector3.Zero();
  80128. }
  80129. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80130. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80131. var c = colorVector.scale(deltaSolidAngle);
  80132. this.L00 = this.L00.add(c.scale(0.282095));
  80133. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80134. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80135. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80136. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80137. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80138. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80139. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80140. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80141. };
  80142. SphericalHarmonics.prototype.scale = function (scale) {
  80143. this.L00 = this.L00.scale(scale);
  80144. this.L1_1 = this.L1_1.scale(scale);
  80145. this.L10 = this.L10.scale(scale);
  80146. this.L11 = this.L11.scale(scale);
  80147. this.L2_2 = this.L2_2.scale(scale);
  80148. this.L2_1 = this.L2_1.scale(scale);
  80149. this.L20 = this.L20.scale(scale);
  80150. this.L21 = this.L21.scale(scale);
  80151. this.L22 = this.L22.scale(scale);
  80152. };
  80153. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80154. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80155. //
  80156. // E_lm = A_l * L_lm
  80157. //
  80158. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80159. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80160. // the scaling factors are given in equation 9.
  80161. // Constant (Band 0)
  80162. this.L00 = this.L00.scale(3.141593);
  80163. // Linear (Band 1)
  80164. this.L1_1 = this.L1_1.scale(2.094395);
  80165. this.L10 = this.L10.scale(2.094395);
  80166. this.L11 = this.L11.scale(2.094395);
  80167. // Quadratic (Band 2)
  80168. this.L2_2 = this.L2_2.scale(0.785398);
  80169. this.L2_1 = this.L2_1.scale(0.785398);
  80170. this.L20 = this.L20.scale(0.785398);
  80171. this.L21 = this.L21.scale(0.785398);
  80172. this.L22 = this.L22.scale(0.785398);
  80173. };
  80174. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80175. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80176. // L = (1/pi) * E * rho
  80177. //
  80178. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80179. this.scale(1.0 / Math.PI);
  80180. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80181. // (The pixel shader must apply albedo after texture fetches, etc).
  80182. };
  80183. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80184. var result = new SphericalHarmonics();
  80185. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80186. result.L1_1 = polynomial.y.scale(0.977204);
  80187. result.L10 = polynomial.z.scale(0.977204);
  80188. result.L11 = polynomial.x.scale(0.977204);
  80189. result.L2_2 = polynomial.xy.scale(1.16538);
  80190. result.L2_1 = polynomial.yz.scale(1.16538);
  80191. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80192. result.L21 = polynomial.zx.scale(1.16538);
  80193. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80194. result.scale(Math.PI);
  80195. return result;
  80196. };
  80197. return SphericalHarmonics;
  80198. }());
  80199. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80200. })(BABYLON || (BABYLON = {}));
  80201. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80202. var BABYLON;
  80203. (function (BABYLON) {
  80204. var FileFaceOrientation = /** @class */ (function () {
  80205. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80206. this.name = name;
  80207. this.worldAxisForNormal = worldAxisForNormal;
  80208. this.worldAxisForFileX = worldAxisForFileX;
  80209. this.worldAxisForFileY = worldAxisForFileY;
  80210. }
  80211. return FileFaceOrientation;
  80212. }());
  80213. ;
  80214. /**
  80215. * Helper class dealing with the extraction of spherical polynomial dataArray
  80216. * from a cube map.
  80217. */
  80218. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80219. function CubeMapToSphericalPolynomialTools() {
  80220. }
  80221. /**
  80222. * Converts a texture to the according Spherical Polynomial data.
  80223. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80224. *
  80225. * @param texture The texture to extract the information from.
  80226. * @return The Spherical Polynomial data.
  80227. */
  80228. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80229. if (!texture.isCube) {
  80230. // Only supports cube Textures currently.
  80231. return null;
  80232. }
  80233. var size = texture.getSize().width;
  80234. var right = texture.readPixels(0);
  80235. var left = texture.readPixels(1);
  80236. var up;
  80237. var down;
  80238. if (texture.isRenderTarget) {
  80239. up = texture.readPixels(3);
  80240. down = texture.readPixels(2);
  80241. }
  80242. else {
  80243. up = texture.readPixels(2);
  80244. down = texture.readPixels(3);
  80245. }
  80246. var front = texture.readPixels(4);
  80247. var back = texture.readPixels(5);
  80248. var gammaSpace = texture.gammaSpace;
  80249. // Always read as RGBA.
  80250. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80251. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80252. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80253. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80254. }
  80255. var cubeInfo = {
  80256. size: size,
  80257. right: right,
  80258. left: left,
  80259. up: up,
  80260. down: down,
  80261. front: front,
  80262. back: back,
  80263. format: format,
  80264. type: type,
  80265. gammaSpace: gammaSpace,
  80266. };
  80267. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80268. };
  80269. /**
  80270. * Converts a cubemap to the according Spherical Polynomial data.
  80271. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80272. *
  80273. * @param cubeInfo The Cube map to extract the information from.
  80274. * @return The Spherical Polynomial data.
  80275. */
  80276. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80277. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80278. var totalSolidAngle = 0.0;
  80279. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80280. var du = 2.0 / cubeInfo.size;
  80281. var dv = du;
  80282. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80283. var minUV = du * 0.5 - 1.0;
  80284. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80285. var fileFace = this.FileFaces[faceIndex];
  80286. var dataArray = cubeInfo[fileFace.name];
  80287. var v = minUV;
  80288. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80289. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80290. // Because SP is still linear, so summation is fine in that basis.
  80291. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80292. for (var y = 0; y < cubeInfo.size; y++) {
  80293. var u = minUV;
  80294. for (var x = 0; x < cubeInfo.size; x++) {
  80295. // World direction (not normalised)
  80296. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80297. worldDirection.normalize();
  80298. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80299. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80300. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80301. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80302. // Handle Integer types.
  80303. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80304. r /= 255;
  80305. g /= 255;
  80306. b /= 255;
  80307. }
  80308. // Handle Gamma space textures.
  80309. if (cubeInfo.gammaSpace) {
  80310. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80311. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80312. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80313. }
  80314. var color = new BABYLON.Color3(r, g, b);
  80315. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80316. totalSolidAngle += deltaSolidAngle;
  80317. u += du;
  80318. }
  80319. v += dv;
  80320. }
  80321. }
  80322. // Solid angle for entire sphere is 4*pi
  80323. var sphereSolidAngle = 4.0 * Math.PI;
  80324. // Adjust the solid angle to allow for how many faces we processed.
  80325. var facesProcessed = 6.0;
  80326. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80327. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80328. // This is needed because the numerical integration over the cube uses a
  80329. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80330. // and also to compensate for accumulative error due to float precision in the summation.
  80331. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80332. sphericalHarmonics.scale(correctionFactor);
  80333. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80334. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80335. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80336. };
  80337. CubeMapToSphericalPolynomialTools.FileFaces = [
  80338. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80339. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80340. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80341. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80342. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80343. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80344. ];
  80345. return CubeMapToSphericalPolynomialTools;
  80346. }());
  80347. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80348. })(BABYLON || (BABYLON = {}));
  80349. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80350. var BABYLON;
  80351. (function (BABYLON) {
  80352. /**
  80353. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80354. */
  80355. var PanoramaToCubeMapTools = /** @class */ (function () {
  80356. function PanoramaToCubeMapTools() {
  80357. }
  80358. /**
  80359. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80360. *
  80361. * @param float32Array The source data.
  80362. * @param inputWidth The width of the input panorama.
  80363. * @param inputhHeight The height of the input panorama.
  80364. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80365. * @return The cubemap data
  80366. */
  80367. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80368. if (!float32Array) {
  80369. throw "ConvertPanoramaToCubemap: input cannot be null";
  80370. }
  80371. if (float32Array.length != inputWidth * inputHeight * 3) {
  80372. throw "ConvertPanoramaToCubemap: input size is wrong";
  80373. }
  80374. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80375. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80376. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80377. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80378. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80379. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80380. return {
  80381. front: textureFront,
  80382. back: textureBack,
  80383. left: textureLeft,
  80384. right: textureRight,
  80385. up: textureUp,
  80386. down: textureDown,
  80387. size: size,
  80388. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80389. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80390. gammaSpace: false,
  80391. };
  80392. };
  80393. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80394. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80395. var textureArray = new Float32Array(buffer);
  80396. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80397. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80398. var dy = 1 / texSize;
  80399. var fy = 0;
  80400. for (var y = 0; y < texSize; y++) {
  80401. var xv1 = faceData[0];
  80402. var xv2 = faceData[2];
  80403. for (var x = 0; x < texSize; x++) {
  80404. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80405. v.normalize();
  80406. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80407. // 3 channels per pixels
  80408. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80409. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80410. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80411. xv1 = xv1.add(rotDX1);
  80412. xv2 = xv2.add(rotDX2);
  80413. }
  80414. fy += dy;
  80415. }
  80416. return textureArray;
  80417. };
  80418. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80419. var theta = Math.atan2(vDir.z, vDir.x);
  80420. var phi = Math.acos(vDir.y);
  80421. while (theta < -Math.PI)
  80422. theta += 2 * Math.PI;
  80423. while (theta > Math.PI)
  80424. theta -= 2 * Math.PI;
  80425. var dx = theta / Math.PI;
  80426. var dy = phi / Math.PI;
  80427. // recenter.
  80428. dx = dx * 0.5 + 0.5;
  80429. var px = Math.round(dx * inputWidth);
  80430. if (px < 0)
  80431. px = 0;
  80432. else if (px >= inputWidth)
  80433. px = inputWidth - 1;
  80434. var py = Math.round(dy * inputHeight);
  80435. if (py < 0)
  80436. py = 0;
  80437. else if (py >= inputHeight)
  80438. py = inputHeight - 1;
  80439. var inputY = (inputHeight - py - 1);
  80440. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80441. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80442. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80443. return {
  80444. r: r,
  80445. g: g,
  80446. b: b
  80447. };
  80448. };
  80449. PanoramaToCubeMapTools.FACE_FRONT = [
  80450. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80451. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80452. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80453. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80454. ];
  80455. PanoramaToCubeMapTools.FACE_BACK = [
  80456. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80457. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80458. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80459. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80460. ];
  80461. PanoramaToCubeMapTools.FACE_RIGHT = [
  80462. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80463. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80464. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80465. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80466. ];
  80467. PanoramaToCubeMapTools.FACE_LEFT = [
  80468. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80469. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80470. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80471. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80472. ];
  80473. PanoramaToCubeMapTools.FACE_DOWN = [
  80474. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80475. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80476. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80477. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80478. ];
  80479. PanoramaToCubeMapTools.FACE_UP = [
  80480. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80481. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80482. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80483. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80484. ];
  80485. return PanoramaToCubeMapTools;
  80486. }());
  80487. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80488. })(BABYLON || (BABYLON = {}));
  80489. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80490. var BABYLON;
  80491. (function (BABYLON) {
  80492. ;
  80493. /**
  80494. * This groups tools to convert HDR texture to native colors array.
  80495. */
  80496. var HDRTools = /** @class */ (function () {
  80497. function HDRTools() {
  80498. }
  80499. HDRTools.Ldexp = function (mantissa, exponent) {
  80500. if (exponent > 1023) {
  80501. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80502. }
  80503. if (exponent < -1074) {
  80504. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80505. }
  80506. return mantissa * Math.pow(2, exponent);
  80507. };
  80508. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80509. if (exponent > 0) { /*nonzero pixel*/
  80510. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80511. float32array[index + 0] = red * exponent;
  80512. float32array[index + 1] = green * exponent;
  80513. float32array[index + 2] = blue * exponent;
  80514. }
  80515. else {
  80516. float32array[index + 0] = 0;
  80517. float32array[index + 1] = 0;
  80518. float32array[index + 2] = 0;
  80519. }
  80520. };
  80521. HDRTools.readStringLine = function (uint8array, startIndex) {
  80522. var line = "";
  80523. var character = "";
  80524. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80525. character = String.fromCharCode(uint8array[i]);
  80526. if (character == "\n") {
  80527. break;
  80528. }
  80529. line += character;
  80530. }
  80531. return line;
  80532. };
  80533. /**
  80534. * Reads header information from an RGBE texture stored in a native array.
  80535. * More information on this format are available here:
  80536. * https://en.wikipedia.org/wiki/RGBE_image_format
  80537. *
  80538. * @param uint8array The binary file stored in native array.
  80539. * @return The header information.
  80540. */
  80541. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80542. var height = 0;
  80543. var width = 0;
  80544. var line = this.readStringLine(uint8array, 0);
  80545. if (line[0] != '#' || line[1] != '?') {
  80546. throw "Bad HDR Format.";
  80547. }
  80548. var endOfHeader = false;
  80549. var findFormat = false;
  80550. var lineIndex = 0;
  80551. do {
  80552. lineIndex += (line.length + 1);
  80553. line = this.readStringLine(uint8array, lineIndex);
  80554. if (line == "FORMAT=32-bit_rle_rgbe") {
  80555. findFormat = true;
  80556. }
  80557. else if (line.length == 0) {
  80558. endOfHeader = true;
  80559. }
  80560. } while (!endOfHeader);
  80561. if (!findFormat) {
  80562. throw "HDR Bad header format, unsupported FORMAT";
  80563. }
  80564. lineIndex += (line.length + 1);
  80565. line = this.readStringLine(uint8array, lineIndex);
  80566. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80567. var match = sizeRegexp.exec(line);
  80568. // TODO. Support +Y and -X if needed.
  80569. if (!match || match.length < 3) {
  80570. throw "HDR Bad header format, no size";
  80571. }
  80572. width = parseInt(match[2]);
  80573. height = parseInt(match[1]);
  80574. if (width < 8 || width > 0x7fff) {
  80575. throw "HDR Bad header format, unsupported size";
  80576. }
  80577. lineIndex += (line.length + 1);
  80578. return {
  80579. height: height,
  80580. width: width,
  80581. dataPosition: lineIndex
  80582. };
  80583. };
  80584. /**
  80585. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80586. * This RGBE texture needs to store the information as a panorama.
  80587. *
  80588. * More information on this format are available here:
  80589. * https://en.wikipedia.org/wiki/RGBE_image_format
  80590. *
  80591. * @param buffer The binary file stored in an array buffer.
  80592. * @param size The expected size of the extracted cubemap.
  80593. * @return The Cube Map information.
  80594. */
  80595. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80596. var uint8array = new Uint8Array(buffer);
  80597. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80598. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80599. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80600. return cubeMapData;
  80601. };
  80602. /**
  80603. * Returns the pixels data extracted from an RGBE texture.
  80604. * This pixels will be stored left to right up to down in the R G B order in one array.
  80605. *
  80606. * More information on this format are available here:
  80607. * https://en.wikipedia.org/wiki/RGBE_image_format
  80608. *
  80609. * @param uint8array The binary file stored in an array buffer.
  80610. * @param hdrInfo The header information of the file.
  80611. * @return The pixels data in RGB right to left up to down order.
  80612. */
  80613. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80614. // Keep for multi format supports.
  80615. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80616. };
  80617. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80618. var num_scanlines = hdrInfo.height;
  80619. var scanline_width = hdrInfo.width;
  80620. var a, b, c, d, count;
  80621. var dataIndex = hdrInfo.dataPosition;
  80622. var index = 0, endIndex = 0, i = 0;
  80623. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80624. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80625. // 3 channels of 4 bytes per pixel in float.
  80626. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80627. var resultArray = new Float32Array(resultBuffer);
  80628. // read in each successive scanline
  80629. while (num_scanlines > 0) {
  80630. a = uint8array[dataIndex++];
  80631. b = uint8array[dataIndex++];
  80632. c = uint8array[dataIndex++];
  80633. d = uint8array[dataIndex++];
  80634. if (a != 2 || b != 2 || (c & 0x80)) {
  80635. // this file is not run length encoded
  80636. throw "HDR Bad header format, not RLE";
  80637. }
  80638. if (((c << 8) | d) != scanline_width) {
  80639. throw "HDR Bad header format, wrong scan line width";
  80640. }
  80641. index = 0;
  80642. // read each of the four channels for the scanline into the buffer
  80643. for (i = 0; i < 4; i++) {
  80644. endIndex = (i + 1) * scanline_width;
  80645. while (index < endIndex) {
  80646. a = uint8array[dataIndex++];
  80647. b = uint8array[dataIndex++];
  80648. if (a > 128) {
  80649. // a run of the same value
  80650. count = a - 128;
  80651. if ((count == 0) || (count > endIndex - index)) {
  80652. throw "HDR Bad Format, bad scanline data (run)";
  80653. }
  80654. while (count-- > 0) {
  80655. scanLineArray[index++] = b;
  80656. }
  80657. }
  80658. else {
  80659. // a non-run
  80660. count = a;
  80661. if ((count == 0) || (count > endIndex - index)) {
  80662. throw "HDR Bad Format, bad scanline data (non-run)";
  80663. }
  80664. scanLineArray[index++] = b;
  80665. if (--count > 0) {
  80666. for (var j = 0; j < count; j++) {
  80667. scanLineArray[index++] = uint8array[dataIndex++];
  80668. }
  80669. }
  80670. }
  80671. }
  80672. }
  80673. // now convert data from buffer into floats
  80674. for (i = 0; i < scanline_width; i++) {
  80675. a = scanLineArray[i];
  80676. b = scanLineArray[i + scanline_width];
  80677. c = scanLineArray[i + 2 * scanline_width];
  80678. d = scanLineArray[i + 3 * scanline_width];
  80679. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80680. }
  80681. num_scanlines--;
  80682. }
  80683. return resultArray;
  80684. };
  80685. return HDRTools;
  80686. }());
  80687. BABYLON.HDRTools = HDRTools;
  80688. })(BABYLON || (BABYLON = {}));
  80689. //# sourceMappingURL=babylon.hdr.js.map
  80690. var BABYLON;
  80691. (function (BABYLON) {
  80692. /**
  80693. * This represents a texture coming from an HDR input.
  80694. *
  80695. * The only supported format is currently panorama picture stored in RGBE format.
  80696. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80697. */
  80698. var HDRCubeTexture = /** @class */ (function (_super) {
  80699. __extends(HDRCubeTexture, _super);
  80700. /**
  80701. * Instantiates an HDRTexture from the following parameters.
  80702. *
  80703. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80704. * @param scene The scene the texture will be used in
  80705. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80706. * @param noMipmap Forces to not generate the mipmap if true
  80707. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80708. * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  80709. * @param reserved Reserved flag for internal use.
  80710. */
  80711. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80712. if (noMipmap === void 0) { noMipmap = false; }
  80713. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80714. if (gammaSpace === void 0) { gammaSpace = false; }
  80715. if (reserved === void 0) { reserved = false; }
  80716. if (onLoad === void 0) { onLoad = null; }
  80717. if (onError === void 0) { onError = null; }
  80718. var _this = _super.call(this, scene) || this;
  80719. _this._generateHarmonics = true;
  80720. _this._onLoad = null;
  80721. _this._onError = null;
  80722. /**
  80723. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80724. */
  80725. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80726. _this._isBlocking = true;
  80727. _this._rotationY = 0;
  80728. /**
  80729. * Gets or sets the center of the bounding box associated with the cube texture
  80730. * It must define where the camera used to render the texture was set
  80731. */
  80732. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80733. if (!url) {
  80734. return _this;
  80735. }
  80736. _this.name = url;
  80737. _this.url = url;
  80738. _this.hasAlpha = false;
  80739. _this.isCube = true;
  80740. _this._textureMatrix = BABYLON.Matrix.Identity();
  80741. _this._onLoad = onLoad;
  80742. _this._onError = onError;
  80743. _this.gammaSpace = gammaSpace;
  80744. _this._noMipmap = noMipmap;
  80745. _this._size = size;
  80746. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80747. if (!_this._texture) {
  80748. if (!scene.useDelayedTextureLoading) {
  80749. _this.loadTexture();
  80750. }
  80751. else {
  80752. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80753. }
  80754. }
  80755. return _this;
  80756. }
  80757. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80758. /**
  80759. * Gets wether or not the texture is blocking during loading.
  80760. */
  80761. get: function () {
  80762. return this._isBlocking;
  80763. },
  80764. /**
  80765. * Sets wether or not the texture is blocking during loading.
  80766. */
  80767. set: function (value) {
  80768. this._isBlocking = value;
  80769. },
  80770. enumerable: true,
  80771. configurable: true
  80772. });
  80773. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80774. /**
  80775. * Gets texture matrix rotation angle around Y axis radians.
  80776. */
  80777. get: function () {
  80778. return this._rotationY;
  80779. },
  80780. /**
  80781. * Sets texture matrix rotation angle around Y axis in radians.
  80782. */
  80783. set: function (value) {
  80784. this._rotationY = value;
  80785. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80786. },
  80787. enumerable: true,
  80788. configurable: true
  80789. });
  80790. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80791. get: function () {
  80792. return this._boundingBoxSize;
  80793. },
  80794. /**
  80795. * Gets or sets the size of the bounding box associated with the cube texture
  80796. * When defined, the cubemap will switch to local mode
  80797. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80798. * @example https://www.babylonjs-playground.com/#RNASML
  80799. */
  80800. set: function (value) {
  80801. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80802. return;
  80803. }
  80804. this._boundingBoxSize = value;
  80805. var scene = this.getScene();
  80806. if (scene) {
  80807. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80808. }
  80809. },
  80810. enumerable: true,
  80811. configurable: true
  80812. });
  80813. /**
  80814. * Occurs when the file is raw .hdr file.
  80815. */
  80816. HDRCubeTexture.prototype.loadTexture = function () {
  80817. var _this = this;
  80818. var callback = function (buffer) {
  80819. var scene = _this.getScene();
  80820. if (!scene) {
  80821. return null;
  80822. }
  80823. // Extract the raw linear data.
  80824. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80825. // Generate harmonics if needed.
  80826. if (_this._generateHarmonics) {
  80827. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80828. _this.sphericalPolynomial = sphericalPolynomial;
  80829. }
  80830. var results = [];
  80831. var byteArray = null;
  80832. // Push each faces.
  80833. for (var j = 0; j < 6; j++) {
  80834. // Create uintarray fallback.
  80835. if (!scene.getEngine().getCaps().textureFloat) {
  80836. // 3 channels of 1 bytes per pixel in bytes.
  80837. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80838. byteArray = new Uint8Array(byteBuffer);
  80839. }
  80840. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80841. // If special cases.
  80842. if (_this.gammaSpace || byteArray) {
  80843. for (var i = 0; i < _this._size * _this._size; i++) {
  80844. // Put in gamma space if requested.
  80845. if (_this.gammaSpace) {
  80846. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80847. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80848. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80849. }
  80850. // Convert to int texture for fallback.
  80851. if (byteArray) {
  80852. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80853. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80854. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80855. // May use luminance instead if the result is not accurate.
  80856. var max = Math.max(Math.max(r, g), b);
  80857. if (max > 255) {
  80858. var scale = 255 / max;
  80859. r *= scale;
  80860. g *= scale;
  80861. b *= scale;
  80862. }
  80863. byteArray[(i * 3) + 0] = r;
  80864. byteArray[(i * 3) + 1] = g;
  80865. byteArray[(i * 3) + 2] = b;
  80866. }
  80867. }
  80868. }
  80869. if (byteArray) {
  80870. results.push(byteArray);
  80871. }
  80872. else {
  80873. results.push(dataFace);
  80874. }
  80875. }
  80876. return results;
  80877. };
  80878. var scene = this.getScene();
  80879. if (scene) {
  80880. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
  80881. }
  80882. };
  80883. HDRCubeTexture.prototype.clone = function () {
  80884. var scene = this.getScene();
  80885. if (!scene) {
  80886. return this;
  80887. }
  80888. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80889. // Base texture
  80890. newTexture.level = this.level;
  80891. newTexture.wrapU = this.wrapU;
  80892. newTexture.wrapV = this.wrapV;
  80893. newTexture.coordinatesIndex = this.coordinatesIndex;
  80894. newTexture.coordinatesMode = this.coordinatesMode;
  80895. return newTexture;
  80896. };
  80897. // Methods
  80898. HDRCubeTexture.prototype.delayLoad = function () {
  80899. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80900. return;
  80901. }
  80902. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80903. this._texture = this._getFromCache(this.url, this._noMipmap);
  80904. if (!this._texture) {
  80905. this.loadTexture();
  80906. }
  80907. };
  80908. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80909. return this._textureMatrix;
  80910. };
  80911. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80912. this._textureMatrix = value;
  80913. };
  80914. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80915. var texture = null;
  80916. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80917. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80918. texture.name = parsedTexture.name;
  80919. texture.hasAlpha = parsedTexture.hasAlpha;
  80920. texture.level = parsedTexture.level;
  80921. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80922. texture.isBlocking = parsedTexture.isBlocking;
  80923. }
  80924. if (texture) {
  80925. if (parsedTexture.boundingBoxPosition) {
  80926. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80927. }
  80928. if (parsedTexture.boundingBoxSize) {
  80929. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80930. }
  80931. if (parsedTexture.rotationY) {
  80932. texture.rotationY = parsedTexture.rotationY;
  80933. }
  80934. }
  80935. return texture;
  80936. };
  80937. HDRCubeTexture.prototype.serialize = function () {
  80938. if (!this.name) {
  80939. return null;
  80940. }
  80941. var serializationObject = {};
  80942. serializationObject.name = this.name;
  80943. serializationObject.hasAlpha = this.hasAlpha;
  80944. serializationObject.isCube = true;
  80945. serializationObject.level = this.level;
  80946. serializationObject.size = this._size;
  80947. serializationObject.coordinatesMode = this.coordinatesMode;
  80948. serializationObject.useInGammaSpace = this.gammaSpace;
  80949. serializationObject.generateHarmonics = this._generateHarmonics;
  80950. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80951. serializationObject.noMipmap = this._noMipmap;
  80952. serializationObject.isBlocking = this._isBlocking;
  80953. serializationObject.rotationY = this._rotationY;
  80954. return serializationObject;
  80955. };
  80956. HDRCubeTexture._facesMapping = [
  80957. "right",
  80958. "left",
  80959. "up",
  80960. "down",
  80961. "front",
  80962. "back"
  80963. ];
  80964. return HDRCubeTexture;
  80965. }(BABYLON.BaseTexture));
  80966. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80967. })(BABYLON || (BABYLON = {}));
  80968. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80969. var BABYLON;
  80970. (function (BABYLON) {
  80971. var IndexedVector2 = /** @class */ (function (_super) {
  80972. __extends(IndexedVector2, _super);
  80973. function IndexedVector2(original, index) {
  80974. var _this = _super.call(this, original.x, original.y) || this;
  80975. _this.index = index;
  80976. return _this;
  80977. }
  80978. return IndexedVector2;
  80979. }(BABYLON.Vector2));
  80980. var PolygonPoints = /** @class */ (function () {
  80981. function PolygonPoints() {
  80982. this.elements = new Array();
  80983. }
  80984. PolygonPoints.prototype.add = function (originalPoints) {
  80985. var _this = this;
  80986. var result = new Array();
  80987. originalPoints.forEach(function (point) {
  80988. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80989. var newPoint = new IndexedVector2(point, _this.elements.length);
  80990. result.push(newPoint);
  80991. _this.elements.push(newPoint);
  80992. }
  80993. });
  80994. return result;
  80995. };
  80996. PolygonPoints.prototype.computeBounds = function () {
  80997. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80998. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80999. this.elements.forEach(function (point) {
  81000. // x
  81001. if (point.x < lmin.x) {
  81002. lmin.x = point.x;
  81003. }
  81004. else if (point.x > lmax.x) {
  81005. lmax.x = point.x;
  81006. }
  81007. // y
  81008. if (point.y < lmin.y) {
  81009. lmin.y = point.y;
  81010. }
  81011. else if (point.y > lmax.y) {
  81012. lmax.y = point.y;
  81013. }
  81014. });
  81015. return {
  81016. min: lmin,
  81017. max: lmax,
  81018. width: lmax.x - lmin.x,
  81019. height: lmax.y - lmin.y
  81020. };
  81021. };
  81022. return PolygonPoints;
  81023. }());
  81024. var Polygon = /** @class */ (function () {
  81025. function Polygon() {
  81026. }
  81027. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  81028. return [
  81029. new BABYLON.Vector2(xmin, ymin),
  81030. new BABYLON.Vector2(xmax, ymin),
  81031. new BABYLON.Vector2(xmax, ymax),
  81032. new BABYLON.Vector2(xmin, ymax)
  81033. ];
  81034. };
  81035. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  81036. if (cx === void 0) { cx = 0; }
  81037. if (cy === void 0) { cy = 0; }
  81038. if (numberOfSides === void 0) { numberOfSides = 32; }
  81039. var result = new Array();
  81040. var angle = 0;
  81041. var increment = (Math.PI * 2) / numberOfSides;
  81042. for (var i = 0; i < numberOfSides; i++) {
  81043. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  81044. angle -= increment;
  81045. }
  81046. return result;
  81047. };
  81048. Polygon.Parse = function (input) {
  81049. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  81050. var i, result = [];
  81051. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  81052. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  81053. }
  81054. return result;
  81055. };
  81056. Polygon.StartingAt = function (x, y) {
  81057. return BABYLON.Path2.StartingAt(x, y);
  81058. };
  81059. return Polygon;
  81060. }());
  81061. BABYLON.Polygon = Polygon;
  81062. var PolygonMeshBuilder = /** @class */ (function () {
  81063. function PolygonMeshBuilder(name, contours, scene) {
  81064. this._points = new PolygonPoints();
  81065. this._outlinepoints = new PolygonPoints();
  81066. this._holes = new Array();
  81067. this._epoints = new Array();
  81068. this._eholes = new Array();
  81069. this._name = name;
  81070. this._scene = scene;
  81071. var points;
  81072. if (contours instanceof BABYLON.Path2) {
  81073. points = contours.getPoints();
  81074. }
  81075. else {
  81076. points = contours;
  81077. }
  81078. this._addToepoint(points);
  81079. this._points.add(points);
  81080. this._outlinepoints.add(points);
  81081. if (typeof earcut === 'undefined') {
  81082. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  81083. }
  81084. }
  81085. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  81086. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  81087. var p = points_1[_i];
  81088. this._epoints.push(p.x, p.y);
  81089. }
  81090. };
  81091. PolygonMeshBuilder.prototype.addHole = function (hole) {
  81092. this._points.add(hole);
  81093. var holepoints = new PolygonPoints();
  81094. holepoints.add(hole);
  81095. this._holes.push(holepoints);
  81096. this._eholes.push(this._epoints.length / 2);
  81097. this._addToepoint(hole);
  81098. return this;
  81099. };
  81100. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  81101. var _this = this;
  81102. if (updatable === void 0) { updatable = false; }
  81103. if (depth === void 0) { depth = 0; }
  81104. var result = new BABYLON.Mesh(this._name, this._scene);
  81105. var normals = new Array();
  81106. var positions = new Array();
  81107. var uvs = new Array();
  81108. var bounds = this._points.computeBounds();
  81109. this._points.elements.forEach(function (p) {
  81110. normals.push(0, 1.0, 0);
  81111. positions.push(p.x, 0, p.y);
  81112. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  81113. });
  81114. var indices = new Array();
  81115. var res = earcut(this._epoints, this._eholes, 2);
  81116. for (var i = 0; i < res.length; i++) {
  81117. indices.push(res[i]);
  81118. }
  81119. if (depth > 0) {
  81120. var positionscount = (positions.length / 3); //get the current pointcount
  81121. this._points.elements.forEach(function (p) {
  81122. normals.push(0, -1.0, 0);
  81123. positions.push(p.x, -depth, p.y);
  81124. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  81125. });
  81126. var totalCount = indices.length;
  81127. for (var i = 0; i < totalCount; i += 3) {
  81128. var i0 = indices[i + 0];
  81129. var i1 = indices[i + 1];
  81130. var i2 = indices[i + 2];
  81131. indices.push(i2 + positionscount);
  81132. indices.push(i1 + positionscount);
  81133. indices.push(i0 + positionscount);
  81134. }
  81135. //Add the sides
  81136. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  81137. this._holes.forEach(function (hole) {
  81138. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  81139. });
  81140. }
  81141. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  81142. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  81143. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  81144. result.setIndices(indices);
  81145. return result;
  81146. };
  81147. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  81148. var StartIndex = positions.length / 3;
  81149. var ulength = 0;
  81150. for (var i = 0; i < points.elements.length; i++) {
  81151. var p = points.elements[i];
  81152. var p1;
  81153. if ((i + 1) > points.elements.length - 1) {
  81154. p1 = points.elements[0];
  81155. }
  81156. else {
  81157. p1 = points.elements[i + 1];
  81158. }
  81159. positions.push(p.x, 0, p.y);
  81160. positions.push(p.x, -depth, p.y);
  81161. positions.push(p1.x, 0, p1.y);
  81162. positions.push(p1.x, -depth, p1.y);
  81163. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  81164. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  81165. var v3 = v2.subtract(v1);
  81166. var v4 = new BABYLON.Vector3(0, 1, 0);
  81167. var vn = BABYLON.Vector3.Cross(v3, v4);
  81168. vn = vn.normalize();
  81169. uvs.push(ulength / bounds.width, 0);
  81170. uvs.push(ulength / bounds.width, 1);
  81171. ulength += v3.length();
  81172. uvs.push((ulength / bounds.width), 0);
  81173. uvs.push((ulength / bounds.width), 1);
  81174. if (!flip) {
  81175. normals.push(-vn.x, -vn.y, -vn.z);
  81176. normals.push(-vn.x, -vn.y, -vn.z);
  81177. normals.push(-vn.x, -vn.y, -vn.z);
  81178. normals.push(-vn.x, -vn.y, -vn.z);
  81179. indices.push(StartIndex);
  81180. indices.push(StartIndex + 1);
  81181. indices.push(StartIndex + 2);
  81182. indices.push(StartIndex + 1);
  81183. indices.push(StartIndex + 3);
  81184. indices.push(StartIndex + 2);
  81185. }
  81186. else {
  81187. normals.push(vn.x, vn.y, vn.z);
  81188. normals.push(vn.x, vn.y, vn.z);
  81189. normals.push(vn.x, vn.y, vn.z);
  81190. normals.push(vn.x, vn.y, vn.z);
  81191. indices.push(StartIndex);
  81192. indices.push(StartIndex + 2);
  81193. indices.push(StartIndex + 1);
  81194. indices.push(StartIndex + 1);
  81195. indices.push(StartIndex + 2);
  81196. indices.push(StartIndex + 3);
  81197. }
  81198. StartIndex += 4;
  81199. }
  81200. ;
  81201. };
  81202. return PolygonMeshBuilder;
  81203. }());
  81204. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  81205. })(BABYLON || (BABYLON = {}));
  81206. //# sourceMappingURL=babylon.polygonMesh.js.map
  81207. var BABYLON;
  81208. (function (BABYLON) {
  81209. // Unique ID when we import meshes from Babylon to CSG
  81210. var currentCSGMeshId = 0;
  81211. // # class Vertex
  81212. // Represents a vertex of a polygon. Use your own vertex class instead of this
  81213. // one to provide additional features like texture coordinates and vertex
  81214. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  81215. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  81216. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  81217. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  81218. // is not used anywhere else.
  81219. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  81220. var Vertex = /** @class */ (function () {
  81221. function Vertex(pos, normal, uv) {
  81222. this.pos = pos;
  81223. this.normal = normal;
  81224. this.uv = uv;
  81225. }
  81226. Vertex.prototype.clone = function () {
  81227. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  81228. };
  81229. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  81230. // orientation of a polygon is flipped.
  81231. Vertex.prototype.flip = function () {
  81232. this.normal = this.normal.scale(-1);
  81233. };
  81234. // Create a new vertex between this vertex and `other` by linearly
  81235. // interpolating all properties using a parameter of `t`. Subclasses should
  81236. // override this to interpolate additional properties.
  81237. Vertex.prototype.interpolate = function (other, t) {
  81238. 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));
  81239. };
  81240. return Vertex;
  81241. }());
  81242. // # class Plane
  81243. // Represents a plane in 3D space.
  81244. var Plane = /** @class */ (function () {
  81245. function Plane(normal, w) {
  81246. this.normal = normal;
  81247. this.w = w;
  81248. }
  81249. Plane.FromPoints = function (a, b, c) {
  81250. var v0 = c.subtract(a);
  81251. var v1 = b.subtract(a);
  81252. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  81253. return null;
  81254. }
  81255. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  81256. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  81257. };
  81258. Plane.prototype.clone = function () {
  81259. return new Plane(this.normal.clone(), this.w);
  81260. };
  81261. Plane.prototype.flip = function () {
  81262. this.normal.scaleInPlace(-1);
  81263. this.w = -this.w;
  81264. };
  81265. // Split `polygon` by this plane if needed, then put the polygon or polygon
  81266. // fragments in the appropriate lists. Coplanar polygons go into either
  81267. // `coplanarFront` or `coplanarBack` depending on their orientation with
  81268. // respect to this plane. Polygons in front or in back of this plane go into
  81269. // either `front` or `back`.
  81270. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  81271. var COPLANAR = 0;
  81272. var FRONT = 1;
  81273. var BACK = 2;
  81274. var SPANNING = 3;
  81275. // Classify each point as well as the entire polygon into one of the above
  81276. // four classes.
  81277. var polygonType = 0;
  81278. var types = [];
  81279. var i;
  81280. var t;
  81281. for (i = 0; i < polygon.vertices.length; i++) {
  81282. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  81283. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  81284. polygonType |= type;
  81285. types.push(type);
  81286. }
  81287. // Put the polygon in the correct list, splitting it when necessary.
  81288. switch (polygonType) {
  81289. case COPLANAR:
  81290. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  81291. break;
  81292. case FRONT:
  81293. front.push(polygon);
  81294. break;
  81295. case BACK:
  81296. back.push(polygon);
  81297. break;
  81298. case SPANNING:
  81299. var f = [], b = [];
  81300. for (i = 0; i < polygon.vertices.length; i++) {
  81301. var j = (i + 1) % polygon.vertices.length;
  81302. var ti = types[i], tj = types[j];
  81303. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  81304. if (ti !== BACK)
  81305. f.push(vi);
  81306. if (ti !== FRONT)
  81307. b.push(ti !== BACK ? vi.clone() : vi);
  81308. if ((ti | tj) === SPANNING) {
  81309. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  81310. var v = vi.interpolate(vj, t);
  81311. f.push(v);
  81312. b.push(v.clone());
  81313. }
  81314. }
  81315. var poly;
  81316. if (f.length >= 3) {
  81317. poly = new Polygon(f, polygon.shared);
  81318. if (poly.plane)
  81319. front.push(poly);
  81320. }
  81321. if (b.length >= 3) {
  81322. poly = new Polygon(b, polygon.shared);
  81323. if (poly.plane)
  81324. back.push(poly);
  81325. }
  81326. break;
  81327. }
  81328. };
  81329. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  81330. // point is on the plane.
  81331. Plane.EPSILON = 1e-5;
  81332. return Plane;
  81333. }());
  81334. // # class Polygon
  81335. // Represents a convex polygon. The vertices used to initialize a polygon must
  81336. // be coplanar and form a convex loop.
  81337. //
  81338. // Each convex polygon has a `shared` property, which is shared between all
  81339. // polygons that are clones of each other or were split from the same polygon.
  81340. // This can be used to define per-polygon properties (such as surface color).
  81341. var Polygon = /** @class */ (function () {
  81342. function Polygon(vertices, shared) {
  81343. this.vertices = vertices;
  81344. this.shared = shared;
  81345. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  81346. }
  81347. Polygon.prototype.clone = function () {
  81348. var vertices = this.vertices.map(function (v) { return v.clone(); });
  81349. return new Polygon(vertices, this.shared);
  81350. };
  81351. Polygon.prototype.flip = function () {
  81352. this.vertices.reverse().map(function (v) { v.flip(); });
  81353. this.plane.flip();
  81354. };
  81355. return Polygon;
  81356. }());
  81357. // # class Node
  81358. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  81359. // by picking a polygon to split along. That polygon (and all other coplanar
  81360. // polygons) are added directly to that node and the other polygons are added to
  81361. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  81362. // no distinction between internal and leaf nodes.
  81363. var Node = /** @class */ (function () {
  81364. function Node(polygons) {
  81365. this.plane = null;
  81366. this.front = null;
  81367. this.back = null;
  81368. this.polygons = new Array();
  81369. if (polygons) {
  81370. this.build(polygons);
  81371. }
  81372. }
  81373. Node.prototype.clone = function () {
  81374. var node = new Node();
  81375. node.plane = this.plane && this.plane.clone();
  81376. node.front = this.front && this.front.clone();
  81377. node.back = this.back && this.back.clone();
  81378. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  81379. return node;
  81380. };
  81381. // Convert solid space to empty space and empty space to solid space.
  81382. Node.prototype.invert = function () {
  81383. for (var i = 0; i < this.polygons.length; i++) {
  81384. this.polygons[i].flip();
  81385. }
  81386. if (this.plane) {
  81387. this.plane.flip();
  81388. }
  81389. if (this.front) {
  81390. this.front.invert();
  81391. }
  81392. if (this.back) {
  81393. this.back.invert();
  81394. }
  81395. var temp = this.front;
  81396. this.front = this.back;
  81397. this.back = temp;
  81398. };
  81399. // Recursively remove all polygons in `polygons` that are inside this BSP
  81400. // tree.
  81401. Node.prototype.clipPolygons = function (polygons) {
  81402. if (!this.plane)
  81403. return polygons.slice();
  81404. var front = new Array(), back = new Array();
  81405. for (var i = 0; i < polygons.length; i++) {
  81406. this.plane.splitPolygon(polygons[i], front, back, front, back);
  81407. }
  81408. if (this.front) {
  81409. front = this.front.clipPolygons(front);
  81410. }
  81411. if (this.back) {
  81412. back = this.back.clipPolygons(back);
  81413. }
  81414. else {
  81415. back = [];
  81416. }
  81417. return front.concat(back);
  81418. };
  81419. // Remove all polygons in this BSP tree that are inside the other BSP tree
  81420. // `bsp`.
  81421. Node.prototype.clipTo = function (bsp) {
  81422. this.polygons = bsp.clipPolygons(this.polygons);
  81423. if (this.front)
  81424. this.front.clipTo(bsp);
  81425. if (this.back)
  81426. this.back.clipTo(bsp);
  81427. };
  81428. // Return a list of all polygons in this BSP tree.
  81429. Node.prototype.allPolygons = function () {
  81430. var polygons = this.polygons.slice();
  81431. if (this.front)
  81432. polygons = polygons.concat(this.front.allPolygons());
  81433. if (this.back)
  81434. polygons = polygons.concat(this.back.allPolygons());
  81435. return polygons;
  81436. };
  81437. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81438. // new polygons are filtered down to the bottom of the tree and become new
  81439. // nodes there. Each set of polygons is partitioned using the first polygon
  81440. // (no heuristic is used to pick a good split).
  81441. Node.prototype.build = function (polygons) {
  81442. if (!polygons.length)
  81443. return;
  81444. if (!this.plane)
  81445. this.plane = polygons[0].plane.clone();
  81446. var front = new Array(), back = new Array();
  81447. for (var i = 0; i < polygons.length; i++) {
  81448. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81449. }
  81450. if (front.length) {
  81451. if (!this.front)
  81452. this.front = new Node();
  81453. this.front.build(front);
  81454. }
  81455. if (back.length) {
  81456. if (!this.back)
  81457. this.back = new Node();
  81458. this.back.build(back);
  81459. }
  81460. };
  81461. return Node;
  81462. }());
  81463. var CSG = /** @class */ (function () {
  81464. function CSG() {
  81465. this.polygons = new Array();
  81466. }
  81467. // Convert BABYLON.Mesh to BABYLON.CSG
  81468. CSG.FromMesh = function (mesh) {
  81469. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81470. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81471. if (mesh instanceof BABYLON.Mesh) {
  81472. mesh.computeWorldMatrix(true);
  81473. matrix = mesh.getWorldMatrix();
  81474. meshPosition = mesh.position.clone();
  81475. meshRotation = mesh.rotation.clone();
  81476. if (mesh.rotationQuaternion) {
  81477. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81478. }
  81479. meshScaling = mesh.scaling.clone();
  81480. }
  81481. else {
  81482. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81483. }
  81484. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81485. var subMeshes = mesh.subMeshes;
  81486. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81487. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81488. vertices = [];
  81489. for (var j = 0; j < 3; j++) {
  81490. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81491. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81492. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81493. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81494. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81495. vertex = new Vertex(position, normal, uv);
  81496. vertices.push(vertex);
  81497. }
  81498. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81499. // To handle the case of degenerated triangle
  81500. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81501. if (polygon.plane)
  81502. polygons.push(polygon);
  81503. }
  81504. }
  81505. var csg = CSG.FromPolygons(polygons);
  81506. csg.matrix = matrix;
  81507. csg.position = meshPosition;
  81508. csg.rotation = meshRotation;
  81509. csg.scaling = meshScaling;
  81510. csg.rotationQuaternion = meshRotationQuaternion;
  81511. currentCSGMeshId++;
  81512. return csg;
  81513. };
  81514. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81515. CSG.FromPolygons = function (polygons) {
  81516. var csg = new CSG();
  81517. csg.polygons = polygons;
  81518. return csg;
  81519. };
  81520. CSG.prototype.clone = function () {
  81521. var csg = new CSG();
  81522. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81523. csg.copyTransformAttributes(this);
  81524. return csg;
  81525. };
  81526. CSG.prototype.union = function (csg) {
  81527. var a = new Node(this.clone().polygons);
  81528. var b = new Node(csg.clone().polygons);
  81529. a.clipTo(b);
  81530. b.clipTo(a);
  81531. b.invert();
  81532. b.clipTo(a);
  81533. b.invert();
  81534. a.build(b.allPolygons());
  81535. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81536. };
  81537. CSG.prototype.unionInPlace = function (csg) {
  81538. var a = new Node(this.polygons);
  81539. var b = new Node(csg.polygons);
  81540. a.clipTo(b);
  81541. b.clipTo(a);
  81542. b.invert();
  81543. b.clipTo(a);
  81544. b.invert();
  81545. a.build(b.allPolygons());
  81546. this.polygons = a.allPolygons();
  81547. };
  81548. CSG.prototype.subtract = function (csg) {
  81549. var a = new Node(this.clone().polygons);
  81550. var b = new Node(csg.clone().polygons);
  81551. a.invert();
  81552. a.clipTo(b);
  81553. b.clipTo(a);
  81554. b.invert();
  81555. b.clipTo(a);
  81556. b.invert();
  81557. a.build(b.allPolygons());
  81558. a.invert();
  81559. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81560. };
  81561. CSG.prototype.subtractInPlace = function (csg) {
  81562. var a = new Node(this.polygons);
  81563. var b = new Node(csg.polygons);
  81564. a.invert();
  81565. a.clipTo(b);
  81566. b.clipTo(a);
  81567. b.invert();
  81568. b.clipTo(a);
  81569. b.invert();
  81570. a.build(b.allPolygons());
  81571. a.invert();
  81572. this.polygons = a.allPolygons();
  81573. };
  81574. CSG.prototype.intersect = function (csg) {
  81575. var a = new Node(this.clone().polygons);
  81576. var b = new Node(csg.clone().polygons);
  81577. a.invert();
  81578. b.clipTo(a);
  81579. b.invert();
  81580. a.clipTo(b);
  81581. b.clipTo(a);
  81582. a.build(b.allPolygons());
  81583. a.invert();
  81584. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81585. };
  81586. CSG.prototype.intersectInPlace = function (csg) {
  81587. var a = new Node(this.polygons);
  81588. var b = new Node(csg.polygons);
  81589. a.invert();
  81590. b.clipTo(a);
  81591. b.invert();
  81592. a.clipTo(b);
  81593. b.clipTo(a);
  81594. a.build(b.allPolygons());
  81595. a.invert();
  81596. this.polygons = a.allPolygons();
  81597. };
  81598. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81599. // not modified.
  81600. CSG.prototype.inverse = function () {
  81601. var csg = this.clone();
  81602. csg.inverseInPlace();
  81603. return csg;
  81604. };
  81605. CSG.prototype.inverseInPlace = function () {
  81606. this.polygons.map(function (p) { p.flip(); });
  81607. };
  81608. // This is used to keep meshes transformations so they can be restored
  81609. // when we build back a Babylon Mesh
  81610. // NB : All CSG operations are performed in world coordinates
  81611. CSG.prototype.copyTransformAttributes = function (csg) {
  81612. this.matrix = csg.matrix;
  81613. this.position = csg.position;
  81614. this.rotation = csg.rotation;
  81615. this.scaling = csg.scaling;
  81616. this.rotationQuaternion = csg.rotationQuaternion;
  81617. return this;
  81618. };
  81619. // Build Raw mesh from CSG
  81620. // Coordinates here are in world space
  81621. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81622. var matrix = this.matrix.clone();
  81623. matrix.invert();
  81624. 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;
  81625. if (keepSubMeshes) {
  81626. // Sort Polygons, since subMeshes are indices range
  81627. polygons.sort(function (a, b) {
  81628. if (a.shared.meshId === b.shared.meshId) {
  81629. return a.shared.subMeshId - b.shared.subMeshId;
  81630. }
  81631. else {
  81632. return a.shared.meshId - b.shared.meshId;
  81633. }
  81634. });
  81635. }
  81636. for (var i = 0, il = polygons.length; i < il; i++) {
  81637. polygon = polygons[i];
  81638. // Building SubMeshes
  81639. if (!subMesh_dict[polygon.shared.meshId]) {
  81640. subMesh_dict[polygon.shared.meshId] = {};
  81641. }
  81642. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81643. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81644. indexStart: +Infinity,
  81645. indexEnd: -Infinity,
  81646. materialIndex: polygon.shared.materialIndex
  81647. };
  81648. }
  81649. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81650. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81651. polygonIndices[0] = 0;
  81652. polygonIndices[1] = j - 1;
  81653. polygonIndices[2] = j;
  81654. for (var k = 0; k < 3; k++) {
  81655. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81656. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81657. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81658. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81659. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81660. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81661. // Check if 2 points can be merged
  81662. if (!(typeof vertex_idx !== 'undefined' &&
  81663. normals[vertex_idx * 3] === localNormal.x &&
  81664. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81665. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81666. uvs[vertex_idx * 2] === uv.x &&
  81667. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81668. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81669. uvs.push(uv.x, uv.y);
  81670. normals.push(normal.x, normal.y, normal.z);
  81671. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81672. }
  81673. indices.push(vertex_idx);
  81674. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81675. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81676. currentIndex++;
  81677. }
  81678. }
  81679. }
  81680. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81681. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81682. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81683. mesh.setIndices(indices, null);
  81684. if (keepSubMeshes) {
  81685. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81686. var materialIndexOffset = 0, materialMaxIndex;
  81687. mesh.subMeshes = new Array();
  81688. for (var m in subMesh_dict) {
  81689. materialMaxIndex = -1;
  81690. for (var sm in subMesh_dict[m]) {
  81691. subMesh_obj = subMesh_dict[m][sm];
  81692. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81693. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81694. }
  81695. materialIndexOffset += ++materialMaxIndex;
  81696. }
  81697. }
  81698. return mesh;
  81699. };
  81700. // Build Mesh from CSG taking material and transforms into account
  81701. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81702. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81703. mesh.material = material;
  81704. mesh.position.copyFrom(this.position);
  81705. mesh.rotation.copyFrom(this.rotation);
  81706. if (this.rotationQuaternion) {
  81707. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81708. }
  81709. mesh.scaling.copyFrom(this.scaling);
  81710. mesh.computeWorldMatrix(true);
  81711. return mesh;
  81712. };
  81713. return CSG;
  81714. }());
  81715. BABYLON.CSG = CSG;
  81716. })(BABYLON || (BABYLON = {}));
  81717. //# sourceMappingURL=babylon.csg.js.map
  81718. var BABYLON;
  81719. (function (BABYLON) {
  81720. var LensFlare = /** @class */ (function () {
  81721. function LensFlare(size, position, color, imgUrl, system) {
  81722. this.size = size;
  81723. this.position = position;
  81724. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81725. this.color = color || new BABYLON.Color3(1, 1, 1);
  81726. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81727. this._system = system;
  81728. system.lensFlares.push(this);
  81729. }
  81730. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81731. return new LensFlare(size, position, color, imgUrl, system);
  81732. };
  81733. LensFlare.prototype.dispose = function () {
  81734. if (this.texture) {
  81735. this.texture.dispose();
  81736. }
  81737. // Remove from scene
  81738. var index = this._system.lensFlares.indexOf(this);
  81739. this._system.lensFlares.splice(index, 1);
  81740. };
  81741. ;
  81742. return LensFlare;
  81743. }());
  81744. BABYLON.LensFlare = LensFlare;
  81745. })(BABYLON || (BABYLON = {}));
  81746. //# sourceMappingURL=babylon.lensFlare.js.map
  81747. var BABYLON;
  81748. (function (BABYLON) {
  81749. var LensFlareSystem = /** @class */ (function () {
  81750. function LensFlareSystem(name, emitter, scene) {
  81751. this.name = name;
  81752. this.lensFlares = new Array();
  81753. this.borderLimit = 300;
  81754. this.viewportBorder = 0;
  81755. this.layerMask = 0x0FFFFFFF;
  81756. this._vertexBuffers = {};
  81757. this._isEnabled = true;
  81758. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81759. this._emitter = emitter;
  81760. this.id = name;
  81761. scene.lensFlareSystems.push(this);
  81762. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81763. var engine = scene.getEngine();
  81764. // VBO
  81765. var vertices = [];
  81766. vertices.push(1, 1);
  81767. vertices.push(-1, 1);
  81768. vertices.push(-1, -1);
  81769. vertices.push(1, -1);
  81770. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81771. // Indices
  81772. var indices = [];
  81773. indices.push(0);
  81774. indices.push(1);
  81775. indices.push(2);
  81776. indices.push(0);
  81777. indices.push(2);
  81778. indices.push(3);
  81779. this._indexBuffer = engine.createIndexBuffer(indices);
  81780. // Effects
  81781. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81782. }
  81783. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81784. get: function () {
  81785. return this._isEnabled;
  81786. },
  81787. set: function (value) {
  81788. this._isEnabled = value;
  81789. },
  81790. enumerable: true,
  81791. configurable: true
  81792. });
  81793. LensFlareSystem.prototype.getScene = function () {
  81794. return this._scene;
  81795. };
  81796. LensFlareSystem.prototype.getEmitter = function () {
  81797. return this._emitter;
  81798. };
  81799. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81800. this._emitter = newEmitter;
  81801. };
  81802. LensFlareSystem.prototype.getEmitterPosition = function () {
  81803. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81804. };
  81805. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81806. var position = this.getEmitterPosition();
  81807. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81808. this._positionX = position.x;
  81809. this._positionY = position.y;
  81810. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81811. if (this.viewportBorder > 0) {
  81812. globalViewport.x -= this.viewportBorder;
  81813. globalViewport.y -= this.viewportBorder;
  81814. globalViewport.width += this.viewportBorder * 2;
  81815. globalViewport.height += this.viewportBorder * 2;
  81816. position.x += this.viewportBorder;
  81817. position.y += this.viewportBorder;
  81818. this._positionX += this.viewportBorder;
  81819. this._positionY += this.viewportBorder;
  81820. }
  81821. if (position.z > 0) {
  81822. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81823. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81824. return true;
  81825. }
  81826. return true;
  81827. }
  81828. return false;
  81829. };
  81830. LensFlareSystem.prototype._isVisible = function () {
  81831. if (!this._isEnabled || !this._scene.activeCamera) {
  81832. return false;
  81833. }
  81834. var emitterPosition = this.getEmitterPosition();
  81835. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81836. var distance = direction.length();
  81837. direction.normalize();
  81838. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81839. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81840. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81841. };
  81842. LensFlareSystem.prototype.render = function () {
  81843. if (!this._effect.isReady() || !this._scene.activeCamera)
  81844. return false;
  81845. var engine = this._scene.getEngine();
  81846. var viewport = this._scene.activeCamera.viewport;
  81847. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81848. // Position
  81849. if (!this.computeEffectivePosition(globalViewport)) {
  81850. return false;
  81851. }
  81852. // Visibility
  81853. if (!this._isVisible()) {
  81854. return false;
  81855. }
  81856. // Intensity
  81857. var awayX;
  81858. var awayY;
  81859. if (this._positionX < this.borderLimit + globalViewport.x) {
  81860. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81861. }
  81862. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81863. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81864. }
  81865. else {
  81866. awayX = 0;
  81867. }
  81868. if (this._positionY < this.borderLimit + globalViewport.y) {
  81869. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81870. }
  81871. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81872. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81873. }
  81874. else {
  81875. awayY = 0;
  81876. }
  81877. var away = (awayX > awayY) ? awayX : awayY;
  81878. away -= this.viewportBorder;
  81879. if (away > this.borderLimit) {
  81880. away = this.borderLimit;
  81881. }
  81882. var intensity = 1.0 - (away / this.borderLimit);
  81883. if (intensity < 0) {
  81884. return false;
  81885. }
  81886. if (intensity > 1.0) {
  81887. intensity = 1.0;
  81888. }
  81889. if (this.viewportBorder > 0) {
  81890. globalViewport.x += this.viewportBorder;
  81891. globalViewport.y += this.viewportBorder;
  81892. globalViewport.width -= this.viewportBorder * 2;
  81893. globalViewport.height -= this.viewportBorder * 2;
  81894. this._positionX -= this.viewportBorder;
  81895. this._positionY -= this.viewportBorder;
  81896. }
  81897. // Position
  81898. var centerX = globalViewport.x + globalViewport.width / 2;
  81899. var centerY = globalViewport.y + globalViewport.height / 2;
  81900. var distX = centerX - this._positionX;
  81901. var distY = centerY - this._positionY;
  81902. // Effects
  81903. engine.enableEffect(this._effect);
  81904. engine.setState(false);
  81905. engine.setDepthBuffer(false);
  81906. // VBOs
  81907. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81908. // Flares
  81909. for (var index = 0; index < this.lensFlares.length; index++) {
  81910. var flare = this.lensFlares[index];
  81911. engine.setAlphaMode(flare.alphaMode);
  81912. var x = centerX - (distX * flare.position);
  81913. var y = centerY - (distY * flare.position);
  81914. var cw = flare.size;
  81915. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81916. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81917. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81918. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81919. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81920. // Texture
  81921. this._effect.setTexture("textureSampler", flare.texture);
  81922. // Color
  81923. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81924. // Draw order
  81925. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81926. }
  81927. engine.setDepthBuffer(true);
  81928. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81929. return true;
  81930. };
  81931. LensFlareSystem.prototype.dispose = function () {
  81932. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81933. if (vertexBuffer) {
  81934. vertexBuffer.dispose();
  81935. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81936. }
  81937. if (this._indexBuffer) {
  81938. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81939. this._indexBuffer = null;
  81940. }
  81941. while (this.lensFlares.length) {
  81942. this.lensFlares[0].dispose();
  81943. }
  81944. // Remove from scene
  81945. var index = this._scene.lensFlareSystems.indexOf(this);
  81946. this._scene.lensFlareSystems.splice(index, 1);
  81947. };
  81948. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81949. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81950. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81951. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81952. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81953. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81954. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81955. var parsedFlare = parsedLensFlareSystem.flares[index];
  81956. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81957. }
  81958. return lensFlareSystem;
  81959. };
  81960. LensFlareSystem.prototype.serialize = function () {
  81961. var serializationObject = {};
  81962. serializationObject.id = this.id;
  81963. serializationObject.name = this.name;
  81964. serializationObject.emitterId = this.getEmitter().id;
  81965. serializationObject.borderLimit = this.borderLimit;
  81966. serializationObject.flares = [];
  81967. for (var index = 0; index < this.lensFlares.length; index++) {
  81968. var flare = this.lensFlares[index];
  81969. serializationObject.flares.push({
  81970. size: flare.size,
  81971. position: flare.position,
  81972. color: flare.color.asArray(),
  81973. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81974. });
  81975. }
  81976. return serializationObject;
  81977. };
  81978. return LensFlareSystem;
  81979. }());
  81980. BABYLON.LensFlareSystem = LensFlareSystem;
  81981. })(BABYLON || (BABYLON = {}));
  81982. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81983. var BABYLON;
  81984. (function (BABYLON) {
  81985. /**
  81986. * This is a holder class for the physics joint created by the physics plugin.
  81987. * It holds a set of functions to control the underlying joint.
  81988. */
  81989. var PhysicsJoint = /** @class */ (function () {
  81990. function PhysicsJoint(type, jointData) {
  81991. this.type = type;
  81992. this.jointData = jointData;
  81993. jointData.nativeParams = jointData.nativeParams || {};
  81994. }
  81995. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81996. get: function () {
  81997. return this._physicsJoint;
  81998. },
  81999. set: function (newJoint) {
  82000. if (this._physicsJoint) {
  82001. //remove from the wolrd
  82002. }
  82003. this._physicsJoint = newJoint;
  82004. },
  82005. enumerable: true,
  82006. configurable: true
  82007. });
  82008. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  82009. set: function (physicsPlugin) {
  82010. this._physicsPlugin = physicsPlugin;
  82011. },
  82012. enumerable: true,
  82013. configurable: true
  82014. });
  82015. /**
  82016. * Execute a function that is physics-plugin specific.
  82017. * @param {Function} func the function that will be executed.
  82018. * It accepts two parameters: the physics world and the physics joint.
  82019. */
  82020. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  82021. func(this._physicsPlugin.world, this._physicsJoint);
  82022. };
  82023. //TODO check if the native joints are the same
  82024. //Joint Types
  82025. PhysicsJoint.DistanceJoint = 0;
  82026. PhysicsJoint.HingeJoint = 1;
  82027. PhysicsJoint.BallAndSocketJoint = 2;
  82028. PhysicsJoint.WheelJoint = 3;
  82029. PhysicsJoint.SliderJoint = 4;
  82030. //OIMO
  82031. PhysicsJoint.PrismaticJoint = 5;
  82032. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  82033. PhysicsJoint.UniversalJoint = 6;
  82034. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  82035. //Cannon
  82036. //Similar to a Ball-Joint. Different in params
  82037. PhysicsJoint.PointToPointJoint = 8;
  82038. //Cannon only at the moment
  82039. PhysicsJoint.SpringJoint = 9;
  82040. PhysicsJoint.LockJoint = 10;
  82041. return PhysicsJoint;
  82042. }());
  82043. BABYLON.PhysicsJoint = PhysicsJoint;
  82044. /**
  82045. * A class representing a physics distance joint.
  82046. */
  82047. var DistanceJoint = /** @class */ (function (_super) {
  82048. __extends(DistanceJoint, _super);
  82049. function DistanceJoint(jointData) {
  82050. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  82051. }
  82052. /**
  82053. * Update the predefined distance.
  82054. */
  82055. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  82056. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  82057. };
  82058. return DistanceJoint;
  82059. }(PhysicsJoint));
  82060. BABYLON.DistanceJoint = DistanceJoint;
  82061. var MotorEnabledJoint = /** @class */ (function (_super) {
  82062. __extends(MotorEnabledJoint, _super);
  82063. function MotorEnabledJoint(type, jointData) {
  82064. return _super.call(this, type, jointData) || this;
  82065. }
  82066. /**
  82067. * Set the motor values.
  82068. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82069. * @param {number} force the force to apply
  82070. * @param {number} maxForce max force for this motor.
  82071. */
  82072. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  82073. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82074. };
  82075. /**
  82076. * Set the motor's limits.
  82077. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82078. */
  82079. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82080. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82081. };
  82082. return MotorEnabledJoint;
  82083. }(PhysicsJoint));
  82084. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  82085. /**
  82086. * This class represents a single hinge physics joint
  82087. */
  82088. var HingeJoint = /** @class */ (function (_super) {
  82089. __extends(HingeJoint, _super);
  82090. function HingeJoint(jointData) {
  82091. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  82092. }
  82093. /**
  82094. * Set the motor values.
  82095. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82096. * @param {number} force the force to apply
  82097. * @param {number} maxForce max force for this motor.
  82098. */
  82099. HingeJoint.prototype.setMotor = function (force, maxForce) {
  82100. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82101. };
  82102. /**
  82103. * Set the motor's limits.
  82104. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82105. */
  82106. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82107. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82108. };
  82109. return HingeJoint;
  82110. }(MotorEnabledJoint));
  82111. BABYLON.HingeJoint = HingeJoint;
  82112. /**
  82113. * This class represents a dual hinge physics joint (same as wheel joint)
  82114. */
  82115. var Hinge2Joint = /** @class */ (function (_super) {
  82116. __extends(Hinge2Joint, _super);
  82117. function Hinge2Joint(jointData) {
  82118. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  82119. }
  82120. /**
  82121. * Set the motor values.
  82122. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82123. * @param {number} force the force to apply
  82124. * @param {number} maxForce max force for this motor.
  82125. * @param {motorIndex} the motor's index, 0 or 1.
  82126. */
  82127. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  82128. if (motorIndex === void 0) { motorIndex = 0; }
  82129. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  82130. };
  82131. /**
  82132. * Set the motor limits.
  82133. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82134. * @param {number} upperLimit the upper limit
  82135. * @param {number} lowerLimit lower limit
  82136. * @param {motorIndex} the motor's index, 0 or 1.
  82137. */
  82138. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  82139. if (motorIndex === void 0) { motorIndex = 0; }
  82140. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  82141. };
  82142. return Hinge2Joint;
  82143. }(MotorEnabledJoint));
  82144. BABYLON.Hinge2Joint = Hinge2Joint;
  82145. })(BABYLON || (BABYLON = {}));
  82146. //# sourceMappingURL=babylon.physicsJoint.js.map
  82147. var BABYLON;
  82148. (function (BABYLON) {
  82149. var PhysicsImpostor = /** @class */ (function () {
  82150. function PhysicsImpostor(object, type, _options, _scene) {
  82151. if (_options === void 0) { _options = { mass: 0 }; }
  82152. var _this = this;
  82153. this.object = object;
  82154. this.type = type;
  82155. this._options = _options;
  82156. this._scene = _scene;
  82157. this._bodyUpdateRequired = false;
  82158. this._onBeforePhysicsStepCallbacks = new Array();
  82159. this._onAfterPhysicsStepCallbacks = new Array();
  82160. this._onPhysicsCollideCallbacks = [];
  82161. this._deltaPosition = BABYLON.Vector3.Zero();
  82162. this._isDisposed = false;
  82163. //temp variables for parent rotation calculations
  82164. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  82165. this._tmpQuat = new BABYLON.Quaternion();
  82166. this._tmpQuat2 = new BABYLON.Quaternion();
  82167. /**
  82168. * this function is executed by the physics engine.
  82169. */
  82170. this.beforeStep = function () {
  82171. if (!_this._physicsEngine) {
  82172. return;
  82173. }
  82174. _this.object.translate(_this._deltaPosition, -1);
  82175. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  82176. _this.object.computeWorldMatrix(false);
  82177. if (_this.object.parent && _this.object.rotationQuaternion) {
  82178. _this.getParentsRotation();
  82179. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  82180. }
  82181. else {
  82182. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  82183. }
  82184. if (!_this._options.disableBidirectionalTransformation) {
  82185. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  82186. }
  82187. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  82188. func(_this);
  82189. });
  82190. };
  82191. /**
  82192. * this function is executed by the physics engine.
  82193. */
  82194. this.afterStep = function () {
  82195. if (!_this._physicsEngine) {
  82196. return;
  82197. }
  82198. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  82199. func(_this);
  82200. });
  82201. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  82202. // object has now its world rotation. needs to be converted to local.
  82203. if (_this.object.parent && _this.object.rotationQuaternion) {
  82204. _this.getParentsRotation();
  82205. _this._tmpQuat.conjugateInPlace();
  82206. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  82207. }
  82208. // take the position set and make it the absolute position of this object.
  82209. _this.object.setAbsolutePosition(_this.object.position);
  82210. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  82211. _this.object.translate(_this._deltaPosition, 1);
  82212. };
  82213. /**
  82214. * Legacy collision detection event support
  82215. */
  82216. this.onCollideEvent = null;
  82217. //event and body object due to cannon's event-based architecture.
  82218. this.onCollide = function (e) {
  82219. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  82220. return;
  82221. }
  82222. if (!_this._physicsEngine) {
  82223. return;
  82224. }
  82225. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  82226. if (otherImpostor) {
  82227. // Legacy collision detection event support
  82228. if (_this.onCollideEvent) {
  82229. _this.onCollideEvent(_this, otherImpostor);
  82230. }
  82231. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  82232. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  82233. }).forEach(function (obj) {
  82234. obj.callback(_this, otherImpostor);
  82235. });
  82236. }
  82237. };
  82238. //sanity check!
  82239. if (!this.object) {
  82240. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  82241. return;
  82242. }
  82243. //legacy support for old syntax.
  82244. if (!this._scene && object.getScene) {
  82245. this._scene = object.getScene();
  82246. }
  82247. if (!this._scene) {
  82248. return;
  82249. }
  82250. this._physicsEngine = this._scene.getPhysicsEngine();
  82251. if (!this._physicsEngine) {
  82252. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  82253. }
  82254. else {
  82255. //set the object's quaternion, if not set
  82256. if (!this.object.rotationQuaternion) {
  82257. if (this.object.rotation) {
  82258. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  82259. }
  82260. else {
  82261. this.object.rotationQuaternion = new BABYLON.Quaternion();
  82262. }
  82263. }
  82264. //default options params
  82265. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  82266. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  82267. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  82268. this._joints = [];
  82269. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  82270. if (!this.object.parent || this._options.ignoreParent) {
  82271. this._init();
  82272. }
  82273. else if (this.object.parent.physicsImpostor) {
  82274. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  82275. }
  82276. }
  82277. }
  82278. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  82279. get: function () {
  82280. return this._isDisposed;
  82281. },
  82282. enumerable: true,
  82283. configurable: true
  82284. });
  82285. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  82286. get: function () {
  82287. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  82288. },
  82289. set: function (value) {
  82290. this.setMass(value);
  82291. },
  82292. enumerable: true,
  82293. configurable: true
  82294. });
  82295. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  82296. get: function () {
  82297. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  82298. },
  82299. set: function (value) {
  82300. if (!this._physicsEngine) {
  82301. return;
  82302. }
  82303. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  82304. },
  82305. enumerable: true,
  82306. configurable: true
  82307. });
  82308. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  82309. get: function () {
  82310. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  82311. },
  82312. set: function (value) {
  82313. if (!this._physicsEngine) {
  82314. return;
  82315. }
  82316. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  82317. },
  82318. enumerable: true,
  82319. configurable: true
  82320. });
  82321. /**
  82322. * This function will completly initialize this impostor.
  82323. * It will create a new body - but only if this mesh has no parent.
  82324. * If it has, this impostor will not be used other than to define the impostor
  82325. * of the child mesh.
  82326. */
  82327. PhysicsImpostor.prototype._init = function () {
  82328. if (!this._physicsEngine) {
  82329. return;
  82330. }
  82331. this._physicsEngine.removeImpostor(this);
  82332. this.physicsBody = null;
  82333. this._parent = this._parent || this._getPhysicsParent();
  82334. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  82335. this._physicsEngine.addImpostor(this);
  82336. }
  82337. };
  82338. PhysicsImpostor.prototype._getPhysicsParent = function () {
  82339. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  82340. var parentMesh = this.object.parent;
  82341. return parentMesh.physicsImpostor;
  82342. }
  82343. return null;
  82344. };
  82345. /**
  82346. * Should a new body be generated.
  82347. */
  82348. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  82349. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  82350. };
  82351. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  82352. this.forceUpdate();
  82353. };
  82354. /**
  82355. * Force a regeneration of this or the parent's impostor's body.
  82356. * Use under cautious - This will remove all joints already implemented.
  82357. */
  82358. PhysicsImpostor.prototype.forceUpdate = function () {
  82359. this._init();
  82360. if (this.parent && !this._options.ignoreParent) {
  82361. this.parent.forceUpdate();
  82362. }
  82363. };
  82364. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  82365. /*public get mesh(): AbstractMesh {
  82366. return this._mesh;
  82367. }*/
  82368. /**
  82369. * Gets the body that holds this impostor. Either its own, or its parent.
  82370. */
  82371. get: function () {
  82372. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  82373. },
  82374. /**
  82375. * Set the physics body. Used mainly by the physics engine/plugin
  82376. */
  82377. set: function (physicsBody) {
  82378. if (this._physicsBody && this._physicsEngine) {
  82379. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  82380. }
  82381. this._physicsBody = physicsBody;
  82382. this.resetUpdateFlags();
  82383. },
  82384. enumerable: true,
  82385. configurable: true
  82386. });
  82387. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  82388. get: function () {
  82389. return !this._options.ignoreParent && this._parent ? this._parent : null;
  82390. },
  82391. set: function (value) {
  82392. this._parent = value;
  82393. },
  82394. enumerable: true,
  82395. configurable: true
  82396. });
  82397. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  82398. this._bodyUpdateRequired = false;
  82399. };
  82400. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  82401. if (this.object.getBoundingInfo) {
  82402. var q = this.object.rotationQuaternion;
  82403. //reset rotation
  82404. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  82405. //calculate the world matrix with no rotation
  82406. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82407. var boundingInfo = this.object.getBoundingInfo();
  82408. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  82409. //bring back the rotation
  82410. this.object.rotationQuaternion = q;
  82411. //calculate the world matrix with the new rotation
  82412. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82413. return size;
  82414. }
  82415. else {
  82416. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  82417. }
  82418. };
  82419. PhysicsImpostor.prototype.getObjectCenter = function () {
  82420. if (this.object.getBoundingInfo) {
  82421. var boundingInfo = this.object.getBoundingInfo();
  82422. return boundingInfo.boundingBox.centerWorld;
  82423. }
  82424. else {
  82425. return this.object.position;
  82426. }
  82427. };
  82428. /**
  82429. * Get a specific parametes from the options parameter.
  82430. */
  82431. PhysicsImpostor.prototype.getParam = function (paramName) {
  82432. return this._options[paramName];
  82433. };
  82434. /**
  82435. * Sets a specific parameter in the options given to the physics plugin
  82436. */
  82437. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82438. this._options[paramName] = value;
  82439. this._bodyUpdateRequired = true;
  82440. };
  82441. /**
  82442. * Specifically change the body's mass option. Won't recreate the physics body object
  82443. */
  82444. PhysicsImpostor.prototype.setMass = function (mass) {
  82445. if (this.getParam("mass") !== mass) {
  82446. this.setParam("mass", mass);
  82447. }
  82448. if (this._physicsEngine) {
  82449. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82450. }
  82451. };
  82452. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82453. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82454. };
  82455. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82456. if (this._physicsEngine) {
  82457. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82458. }
  82459. };
  82460. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82461. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82462. };
  82463. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82464. if (this._physicsEngine) {
  82465. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82466. }
  82467. };
  82468. /**
  82469. * Execute a function with the physics plugin native code.
  82470. * Provide a function the will have two variables - the world object and the physics body object.
  82471. */
  82472. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82473. if (this._physicsEngine) {
  82474. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82475. }
  82476. };
  82477. /**
  82478. * Register a function that will be executed before the physics world is stepping forward.
  82479. */
  82480. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82481. this._onBeforePhysicsStepCallbacks.push(func);
  82482. };
  82483. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82484. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82485. if (index > -1) {
  82486. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82487. }
  82488. else {
  82489. BABYLON.Tools.Warn("Function to remove was not found");
  82490. }
  82491. };
  82492. /**
  82493. * Register a function that will be executed after the physics step
  82494. */
  82495. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82496. this._onAfterPhysicsStepCallbacks.push(func);
  82497. };
  82498. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82499. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82500. if (index > -1) {
  82501. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82502. }
  82503. else {
  82504. BABYLON.Tools.Warn("Function to remove was not found");
  82505. }
  82506. };
  82507. /**
  82508. * register a function that will be executed when this impostor collides against a different body.
  82509. */
  82510. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82511. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82512. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82513. };
  82514. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82515. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82516. var index = -1;
  82517. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  82518. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  82519. // chcek the arrays match
  82520. var sameList = cbDef.otherImpostors.every(function (impostor) {
  82521. return collidedAgainstList.indexOf(impostor) > -1;
  82522. });
  82523. if (sameList) {
  82524. index = idx;
  82525. }
  82526. return sameList;
  82527. }
  82528. return false;
  82529. });
  82530. if (found) {
  82531. this._onPhysicsCollideCallbacks.splice(index, 1);
  82532. }
  82533. else {
  82534. BABYLON.Tools.Warn("Function to remove was not found");
  82535. }
  82536. };
  82537. PhysicsImpostor.prototype.getParentsRotation = function () {
  82538. var parent = this.object.parent;
  82539. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82540. while (parent) {
  82541. if (parent.rotationQuaternion) {
  82542. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82543. }
  82544. else {
  82545. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82546. }
  82547. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82548. parent = parent.parent;
  82549. }
  82550. return this._tmpQuat;
  82551. };
  82552. /**
  82553. * Apply a force
  82554. */
  82555. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82556. if (this._physicsEngine) {
  82557. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82558. }
  82559. return this;
  82560. };
  82561. /**
  82562. * Apply an impulse
  82563. */
  82564. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82565. if (this._physicsEngine) {
  82566. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82567. }
  82568. return this;
  82569. };
  82570. /**
  82571. * A help function to create a joint.
  82572. */
  82573. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82574. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82575. this.addJoint(otherImpostor, joint);
  82576. return this;
  82577. };
  82578. /**
  82579. * Add a joint to this impostor with a different impostor.
  82580. */
  82581. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82582. this._joints.push({
  82583. otherImpostor: otherImpostor,
  82584. joint: joint
  82585. });
  82586. if (this._physicsEngine) {
  82587. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82588. }
  82589. return this;
  82590. };
  82591. /**
  82592. * Will keep this body still, in a sleep mode.
  82593. */
  82594. PhysicsImpostor.prototype.sleep = function () {
  82595. if (this._physicsEngine) {
  82596. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82597. }
  82598. return this;
  82599. };
  82600. /**
  82601. * Wake the body up.
  82602. */
  82603. PhysicsImpostor.prototype.wakeUp = function () {
  82604. if (this._physicsEngine) {
  82605. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82606. }
  82607. return this;
  82608. };
  82609. PhysicsImpostor.prototype.clone = function (newObject) {
  82610. if (!newObject)
  82611. return null;
  82612. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82613. };
  82614. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82615. var _this = this;
  82616. //no dispose if no physics engine is available.
  82617. if (!this._physicsEngine) {
  82618. return;
  82619. }
  82620. this._joints.forEach(function (j) {
  82621. if (_this._physicsEngine) {
  82622. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82623. }
  82624. });
  82625. //dispose the physics body
  82626. this._physicsEngine.removeImpostor(this);
  82627. if (this.parent) {
  82628. this.parent.forceUpdate();
  82629. }
  82630. else {
  82631. /*this._object.getChildMeshes().forEach(function(mesh) {
  82632. if (mesh.physicsImpostor) {
  82633. if (disposeChildren) {
  82634. mesh.physicsImpostor.dispose();
  82635. mesh.physicsImpostor = null;
  82636. }
  82637. }
  82638. })*/
  82639. }
  82640. this._isDisposed = true;
  82641. };
  82642. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82643. this._deltaPosition.copyFrom(position);
  82644. };
  82645. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82646. if (!this._deltaRotation) {
  82647. this._deltaRotation = new BABYLON.Quaternion();
  82648. }
  82649. this._deltaRotation.copyFrom(rotation);
  82650. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82651. };
  82652. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82653. if (this._physicsEngine) {
  82654. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82655. }
  82656. return this;
  82657. };
  82658. PhysicsImpostor.prototype.getRadius = function () {
  82659. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82660. };
  82661. /**
  82662. * Sync a bone with this impostor
  82663. * @param bone The bone to sync to the impostor.
  82664. * @param boneMesh The mesh that the bone is influencing.
  82665. * @param jointPivot The pivot of the joint / bone in local space.
  82666. * @param distToJoint Optional distance from the impostor to the joint.
  82667. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82668. */
  82669. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82670. var tempVec = PhysicsImpostor._tmpVecs[0];
  82671. var mesh = this.object;
  82672. if (mesh.rotationQuaternion) {
  82673. if (adjustRotation) {
  82674. var tempQuat = PhysicsImpostor._tmpQuat;
  82675. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82676. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82677. }
  82678. else {
  82679. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82680. }
  82681. }
  82682. tempVec.x = 0;
  82683. tempVec.y = 0;
  82684. tempVec.z = 0;
  82685. if (jointPivot) {
  82686. tempVec.x = jointPivot.x;
  82687. tempVec.y = jointPivot.y;
  82688. tempVec.z = jointPivot.z;
  82689. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82690. if (distToJoint === undefined || distToJoint === null) {
  82691. distToJoint = jointPivot.length();
  82692. }
  82693. tempVec.x *= distToJoint;
  82694. tempVec.y *= distToJoint;
  82695. tempVec.z *= distToJoint;
  82696. }
  82697. if (bone.getParent()) {
  82698. tempVec.addInPlace(mesh.getAbsolutePosition());
  82699. bone.setAbsolutePosition(tempVec, boneMesh);
  82700. }
  82701. else {
  82702. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82703. boneMesh.position.x -= tempVec.x;
  82704. boneMesh.position.y -= tempVec.y;
  82705. boneMesh.position.z -= tempVec.z;
  82706. }
  82707. };
  82708. /**
  82709. * Sync impostor to a bone
  82710. * @param bone The bone that the impostor will be synced to.
  82711. * @param boneMesh The mesh that the bone is influencing.
  82712. * @param jointPivot The pivot of the joint / bone in local space.
  82713. * @param distToJoint Optional distance from the impostor to the joint.
  82714. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82715. * @param boneAxis Optional vector3 axis the bone is aligned with
  82716. */
  82717. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82718. var mesh = this.object;
  82719. if (mesh.rotationQuaternion) {
  82720. if (adjustRotation) {
  82721. var tempQuat = PhysicsImpostor._tmpQuat;
  82722. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82723. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82724. }
  82725. else {
  82726. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82727. }
  82728. }
  82729. var pos = PhysicsImpostor._tmpVecs[0];
  82730. var boneDir = PhysicsImpostor._tmpVecs[1];
  82731. if (!boneAxis) {
  82732. boneAxis = PhysicsImpostor._tmpVecs[2];
  82733. boneAxis.x = 0;
  82734. boneAxis.y = 1;
  82735. boneAxis.z = 0;
  82736. }
  82737. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82738. bone.getAbsolutePositionToRef(boneMesh, pos);
  82739. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82740. distToJoint = jointPivot.length();
  82741. }
  82742. if (distToJoint !== undefined && distToJoint !== null) {
  82743. pos.x += boneDir.x * distToJoint;
  82744. pos.y += boneDir.y * distToJoint;
  82745. pos.z += boneDir.z * distToJoint;
  82746. }
  82747. mesh.setAbsolutePosition(pos);
  82748. };
  82749. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82750. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82751. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82752. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82753. //Impostor types
  82754. PhysicsImpostor.NoImpostor = 0;
  82755. PhysicsImpostor.SphereImpostor = 1;
  82756. PhysicsImpostor.BoxImpostor = 2;
  82757. PhysicsImpostor.PlaneImpostor = 3;
  82758. PhysicsImpostor.MeshImpostor = 4;
  82759. PhysicsImpostor.CylinderImpostor = 7;
  82760. PhysicsImpostor.ParticleImpostor = 8;
  82761. PhysicsImpostor.HeightmapImpostor = 9;
  82762. return PhysicsImpostor;
  82763. }());
  82764. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82765. })(BABYLON || (BABYLON = {}));
  82766. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82767. var BABYLON;
  82768. (function (BABYLON) {
  82769. var PhysicsEngine = /** @class */ (function () {
  82770. function PhysicsEngine(gravity, _physicsPlugin) {
  82771. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82772. this._physicsPlugin = _physicsPlugin;
  82773. //new methods and parameters
  82774. this._impostors = [];
  82775. this._joints = [];
  82776. if (!this._physicsPlugin.isSupported()) {
  82777. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82778. + "Please make sure it is included.");
  82779. }
  82780. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82781. this.setGravity(gravity);
  82782. this.setTimeStep();
  82783. }
  82784. PhysicsEngine.prototype.setGravity = function (gravity) {
  82785. this.gravity = gravity;
  82786. this._physicsPlugin.setGravity(this.gravity);
  82787. };
  82788. /**
  82789. * Set the time step of the physics engine.
  82790. * default is 1/60.
  82791. * To slow it down, enter 1/600 for example.
  82792. * To speed it up, 1/30
  82793. * @param {number} newTimeStep the new timestep to apply to this world.
  82794. */
  82795. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82796. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82797. this._physicsPlugin.setTimeStep(newTimeStep);
  82798. };
  82799. /**
  82800. * Get the time step of the physics engine.
  82801. */
  82802. PhysicsEngine.prototype.getTimeStep = function () {
  82803. return this._physicsPlugin.getTimeStep();
  82804. };
  82805. PhysicsEngine.prototype.dispose = function () {
  82806. this._impostors.forEach(function (impostor) {
  82807. impostor.dispose();
  82808. });
  82809. this._physicsPlugin.dispose();
  82810. };
  82811. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82812. return this._physicsPlugin.name;
  82813. };
  82814. /**
  82815. * Adding a new impostor for the impostor tracking.
  82816. * This will be done by the impostor itself.
  82817. * @param {PhysicsImpostor} impostor the impostor to add
  82818. */
  82819. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82820. impostor.uniqueId = this._impostors.push(impostor);
  82821. //if no parent, generate the body
  82822. if (!impostor.parent) {
  82823. this._physicsPlugin.generatePhysicsBody(impostor);
  82824. }
  82825. };
  82826. /**
  82827. * Remove an impostor from the engine.
  82828. * This impostor and its mesh will not longer be updated by the physics engine.
  82829. * @param {PhysicsImpostor} impostor the impostor to remove
  82830. */
  82831. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82832. var index = this._impostors.indexOf(impostor);
  82833. if (index > -1) {
  82834. var removed = this._impostors.splice(index, 1);
  82835. //Is it needed?
  82836. if (removed.length) {
  82837. //this will also remove it from the world.
  82838. removed[0].physicsBody = null;
  82839. }
  82840. }
  82841. };
  82842. /**
  82843. * Add a joint to the physics engine
  82844. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82845. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82846. * @param {PhysicsJoint} the joint that will connect both impostors.
  82847. */
  82848. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82849. var impostorJoint = {
  82850. mainImpostor: mainImpostor,
  82851. connectedImpostor: connectedImpostor,
  82852. joint: joint
  82853. };
  82854. joint.physicsPlugin = this._physicsPlugin;
  82855. this._joints.push(impostorJoint);
  82856. this._physicsPlugin.generateJoint(impostorJoint);
  82857. };
  82858. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82859. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82860. return (impostorJoint.connectedImpostor === connectedImpostor
  82861. && impostorJoint.joint === joint
  82862. && impostorJoint.mainImpostor === mainImpostor);
  82863. });
  82864. if (matchingJoints.length) {
  82865. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82866. //TODO remove it from the list as well
  82867. }
  82868. };
  82869. /**
  82870. * Called by the scene. no need to call it.
  82871. */
  82872. PhysicsEngine.prototype._step = function (delta) {
  82873. var _this = this;
  82874. //check if any mesh has no body / requires an update
  82875. this._impostors.forEach(function (impostor) {
  82876. if (impostor.isBodyInitRequired()) {
  82877. _this._physicsPlugin.generatePhysicsBody(impostor);
  82878. }
  82879. });
  82880. if (delta > 0.1) {
  82881. delta = 0.1;
  82882. }
  82883. else if (delta <= 0) {
  82884. delta = 1.0 / 60.0;
  82885. }
  82886. this._physicsPlugin.executeStep(delta, this._impostors);
  82887. };
  82888. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82889. return this._physicsPlugin;
  82890. };
  82891. PhysicsEngine.prototype.getImpostors = function () {
  82892. return this._impostors;
  82893. };
  82894. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82895. for (var i = 0; i < this._impostors.length; ++i) {
  82896. if (this._impostors[i].object === object) {
  82897. return this._impostors[i];
  82898. }
  82899. }
  82900. return null;
  82901. };
  82902. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82903. for (var i = 0; i < this._impostors.length; ++i) {
  82904. if (this._impostors[i].physicsBody === body) {
  82905. return this._impostors[i];
  82906. }
  82907. }
  82908. return null;
  82909. };
  82910. // Statics
  82911. PhysicsEngine.Epsilon = 0.001;
  82912. return PhysicsEngine;
  82913. }());
  82914. BABYLON.PhysicsEngine = PhysicsEngine;
  82915. })(BABYLON || (BABYLON = {}));
  82916. //# sourceMappingURL=babylon.physicsEngine.js.map
  82917. var BABYLON;
  82918. (function (BABYLON) {
  82919. var PhysicsHelper = /** @class */ (function () {
  82920. function PhysicsHelper(scene) {
  82921. this._scene = scene;
  82922. this._physicsEngine = this._scene.getPhysicsEngine();
  82923. if (!this._physicsEngine) {
  82924. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82925. }
  82926. }
  82927. /**
  82928. * @param {Vector3} origin the origin of the explosion
  82929. * @param {number} radius the explosion radius
  82930. * @param {number} strength the explosion strength
  82931. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82932. */
  82933. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82934. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82935. if (!this._physicsEngine) {
  82936. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82937. return null;
  82938. }
  82939. var impostors = this._physicsEngine.getImpostors();
  82940. if (impostors.length === 0) {
  82941. return null;
  82942. }
  82943. var event = new PhysicsRadialExplosionEvent(this._scene);
  82944. impostors.forEach(function (impostor) {
  82945. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82946. if (!impostorForceAndContactPoint) {
  82947. return;
  82948. }
  82949. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82950. });
  82951. event.dispose(false);
  82952. return event;
  82953. };
  82954. /**
  82955. * @param {Vector3} origin the origin of the explosion
  82956. * @param {number} radius the explosion radius
  82957. * @param {number} strength the explosion strength
  82958. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82959. */
  82960. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82961. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82962. if (!this._physicsEngine) {
  82963. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82964. return null;
  82965. }
  82966. var impostors = this._physicsEngine.getImpostors();
  82967. if (impostors.length === 0) {
  82968. return null;
  82969. }
  82970. var event = new PhysicsRadialExplosionEvent(this._scene);
  82971. impostors.forEach(function (impostor) {
  82972. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82973. if (!impostorForceAndContactPoint) {
  82974. return;
  82975. }
  82976. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82977. });
  82978. event.dispose(false);
  82979. return event;
  82980. };
  82981. /**
  82982. * @param {Vector3} origin the origin of the explosion
  82983. * @param {number} radius the explosion radius
  82984. * @param {number} strength the explosion strength
  82985. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82986. */
  82987. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82988. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82989. if (!this._physicsEngine) {
  82990. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82991. return null;
  82992. }
  82993. var impostors = this._physicsEngine.getImpostors();
  82994. if (impostors.length === 0) {
  82995. return null;
  82996. }
  82997. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82998. event.dispose(false);
  82999. return event;
  83000. };
  83001. /**
  83002. * @param {Vector3} origin the origin of the updraft
  83003. * @param {number} radius the radius of the updraft
  83004. * @param {number} strength the strength of the updraft
  83005. * @param {number} height the height of the updraft
  83006. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  83007. */
  83008. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  83009. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  83010. if (!this._physicsEngine) {
  83011. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83012. return null;
  83013. }
  83014. if (this._physicsEngine.getImpostors().length === 0) {
  83015. return null;
  83016. }
  83017. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  83018. event.dispose(false);
  83019. return event;
  83020. };
  83021. /**
  83022. * @param {Vector3} origin the of the vortex
  83023. * @param {number} radius the radius of the vortex
  83024. * @param {number} strength the strength of the vortex
  83025. * @param {number} height the height of the vortex
  83026. */
  83027. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  83028. if (!this._physicsEngine) {
  83029. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83030. return null;
  83031. }
  83032. if (this._physicsEngine.getImpostors().length === 0) {
  83033. return null;
  83034. }
  83035. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  83036. event.dispose(false);
  83037. return event;
  83038. };
  83039. return PhysicsHelper;
  83040. }());
  83041. BABYLON.PhysicsHelper = PhysicsHelper;
  83042. /***** Radial explosion *****/
  83043. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  83044. function PhysicsRadialExplosionEvent(scene) {
  83045. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  83046. this._rays = [];
  83047. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  83048. this._scene = scene;
  83049. }
  83050. /**
  83051. * Returns the data related to the radial explosion event (sphere & rays).
  83052. * @returns {PhysicsRadialExplosionEventData}
  83053. */
  83054. PhysicsRadialExplosionEvent.prototype.getData = function () {
  83055. this._dataFetched = true;
  83056. return {
  83057. sphere: this._sphere,
  83058. rays: this._rays,
  83059. };
  83060. };
  83061. /**
  83062. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  83063. * @param impostor
  83064. * @param {Vector3} origin the origin of the explosion
  83065. * @param {number} radius the explosion radius
  83066. * @param {number} strength the explosion strength
  83067. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  83068. * @returns {Nullable<PhysicsForceAndContactPoint>}
  83069. */
  83070. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  83071. if (impostor.mass === 0) {
  83072. return null;
  83073. }
  83074. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  83075. return null;
  83076. }
  83077. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83078. return null;
  83079. }
  83080. var impostorObjectCenter = impostor.getObjectCenter();
  83081. var direction = impostorObjectCenter.subtract(origin);
  83082. var ray = new BABYLON.Ray(origin, direction, radius);
  83083. this._rays.push(ray);
  83084. var hit = ray.intersectsMesh(impostor.object);
  83085. var contactPoint = hit.pickedPoint;
  83086. if (!contactPoint) {
  83087. return null;
  83088. }
  83089. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  83090. if (distanceFromOrigin > radius) {
  83091. return null;
  83092. }
  83093. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  83094. ? strength
  83095. : strength * (1 - (distanceFromOrigin / radius));
  83096. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83097. return { force: force, contactPoint: contactPoint };
  83098. };
  83099. /**
  83100. * Disposes the sphere.
  83101. * @param {bolean} force
  83102. */
  83103. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  83104. var _this = this;
  83105. if (force === void 0) { force = true; }
  83106. if (force) {
  83107. this._sphere.dispose();
  83108. }
  83109. else {
  83110. setTimeout(function () {
  83111. if (!_this._dataFetched) {
  83112. _this._sphere.dispose();
  83113. }
  83114. }, 0);
  83115. }
  83116. };
  83117. /*** Helpers ***/
  83118. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  83119. if (!this._sphere) {
  83120. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  83121. this._sphere.isVisible = false;
  83122. }
  83123. };
  83124. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  83125. var impostorObject = impostor.object;
  83126. this._prepareSphere();
  83127. this._sphere.position = origin;
  83128. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  83129. this._sphere._updateBoundingInfo();
  83130. this._sphere.computeWorldMatrix(true);
  83131. return this._sphere.intersectsMesh(impostorObject, true);
  83132. };
  83133. return PhysicsRadialExplosionEvent;
  83134. }());
  83135. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  83136. /***** Gravitational Field *****/
  83137. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  83138. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  83139. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83140. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83141. this._physicsHelper = physicsHelper;
  83142. this._scene = scene;
  83143. this._origin = origin;
  83144. this._radius = radius;
  83145. this._strength = strength;
  83146. this._falloff = falloff;
  83147. this._tickCallback = this._tick.bind(this);
  83148. }
  83149. /**
  83150. * Returns the data related to the gravitational field event (sphere).
  83151. * @returns {PhysicsGravitationalFieldEventData}
  83152. */
  83153. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  83154. this._dataFetched = true;
  83155. return {
  83156. sphere: this._sphere,
  83157. };
  83158. };
  83159. /**
  83160. * Enables the gravitational field.
  83161. */
  83162. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  83163. this._tickCallback.call(this);
  83164. this._scene.registerBeforeRender(this._tickCallback);
  83165. };
  83166. /**
  83167. * Disables the gravitational field.
  83168. */
  83169. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  83170. this._scene.unregisterBeforeRender(this._tickCallback);
  83171. };
  83172. /**
  83173. * Disposes the sphere.
  83174. * @param {bolean} force
  83175. */
  83176. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  83177. var _this = this;
  83178. if (force === void 0) { force = true; }
  83179. if (force) {
  83180. this._sphere.dispose();
  83181. }
  83182. else {
  83183. setTimeout(function () {
  83184. if (!_this._dataFetched) {
  83185. _this._sphere.dispose();
  83186. }
  83187. }, 0);
  83188. }
  83189. };
  83190. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  83191. // Since the params won't change, we fetch the event only once
  83192. if (this._sphere) {
  83193. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83194. }
  83195. else {
  83196. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83197. if (radialExplosionEvent) {
  83198. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  83199. }
  83200. }
  83201. };
  83202. return PhysicsGravitationalFieldEvent;
  83203. }());
  83204. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  83205. /***** Updraft *****/
  83206. var PhysicsUpdraftEvent = /** @class */ (function () {
  83207. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  83208. this._scene = _scene;
  83209. this._origin = _origin;
  83210. this._radius = _radius;
  83211. this._strength = _strength;
  83212. this._height = _height;
  83213. this._updraftMode = _updraftMode;
  83214. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83215. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  83216. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83217. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83218. this._physicsEngine = this._scene.getPhysicsEngine();
  83219. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83220. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83221. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83222. this._originDirection = this._origin.subtract(this._originTop).normalize();
  83223. }
  83224. this._tickCallback = this._tick.bind(this);
  83225. }
  83226. /**
  83227. * Returns the data related to the updraft event (cylinder).
  83228. * @returns {PhysicsUpdraftEventData}
  83229. */
  83230. PhysicsUpdraftEvent.prototype.getData = function () {
  83231. this._dataFetched = true;
  83232. return {
  83233. cylinder: this._cylinder,
  83234. };
  83235. };
  83236. /**
  83237. * Enables the updraft.
  83238. */
  83239. PhysicsUpdraftEvent.prototype.enable = function () {
  83240. this._tickCallback.call(this);
  83241. this._scene.registerBeforeRender(this._tickCallback);
  83242. };
  83243. /**
  83244. * Disables the cortex.
  83245. */
  83246. PhysicsUpdraftEvent.prototype.disable = function () {
  83247. this._scene.unregisterBeforeRender(this._tickCallback);
  83248. };
  83249. /**
  83250. * Disposes the sphere.
  83251. * @param {bolean} force
  83252. */
  83253. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  83254. var _this = this;
  83255. if (force === void 0) { force = true; }
  83256. if (force) {
  83257. this._cylinder.dispose();
  83258. }
  83259. else {
  83260. setTimeout(function () {
  83261. if (!_this._dataFetched) {
  83262. _this._cylinder.dispose();
  83263. }
  83264. }, 0);
  83265. }
  83266. };
  83267. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83268. if (impostor.mass === 0) {
  83269. return null;
  83270. }
  83271. if (!this._intersectsWithCylinder(impostor)) {
  83272. return null;
  83273. }
  83274. var impostorObjectCenter = impostor.getObjectCenter();
  83275. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83276. var direction = this._originDirection;
  83277. }
  83278. else {
  83279. var direction = impostorObjectCenter.subtract(this._originTop);
  83280. }
  83281. var multiplier = this._strength * -1;
  83282. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83283. return { force: force, contactPoint: impostorObjectCenter };
  83284. };
  83285. PhysicsUpdraftEvent.prototype._tick = function () {
  83286. var _this = this;
  83287. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83288. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83289. if (!impostorForceAndContactPoint) {
  83290. return;
  83291. }
  83292. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83293. });
  83294. };
  83295. /*** Helpers ***/
  83296. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  83297. if (!this._cylinder) {
  83298. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  83299. height: this._height,
  83300. diameter: this._radius * 2,
  83301. }, this._scene);
  83302. this._cylinder.isVisible = false;
  83303. }
  83304. };
  83305. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  83306. var impostorObject = impostor.object;
  83307. this._prepareCylinder();
  83308. this._cylinder.position = this._cylinderPosition;
  83309. return this._cylinder.intersectsMesh(impostorObject, true);
  83310. };
  83311. return PhysicsUpdraftEvent;
  83312. }());
  83313. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  83314. /***** Vortex *****/
  83315. var PhysicsVortexEvent = /** @class */ (function () {
  83316. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  83317. this._scene = _scene;
  83318. this._origin = _origin;
  83319. this._radius = _radius;
  83320. this._strength = _strength;
  83321. this._height = _height;
  83322. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83323. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  83324. this._updraftMultiplier = 0.02;
  83325. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83326. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83327. this._physicsEngine = this._scene.getPhysicsEngine();
  83328. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83329. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83330. this._tickCallback = this._tick.bind(this);
  83331. }
  83332. /**
  83333. * Returns the data related to the vortex event (cylinder).
  83334. * @returns {PhysicsVortexEventData}
  83335. */
  83336. PhysicsVortexEvent.prototype.getData = function () {
  83337. this._dataFetched = true;
  83338. return {
  83339. cylinder: this._cylinder,
  83340. };
  83341. };
  83342. /**
  83343. * Enables the vortex.
  83344. */
  83345. PhysicsVortexEvent.prototype.enable = function () {
  83346. this._tickCallback.call(this);
  83347. this._scene.registerBeforeRender(this._tickCallback);
  83348. };
  83349. /**
  83350. * Disables the cortex.
  83351. */
  83352. PhysicsVortexEvent.prototype.disable = function () {
  83353. this._scene.unregisterBeforeRender(this._tickCallback);
  83354. };
  83355. /**
  83356. * Disposes the sphere.
  83357. * @param {bolean} force
  83358. */
  83359. PhysicsVortexEvent.prototype.dispose = function (force) {
  83360. var _this = this;
  83361. if (force === void 0) { force = true; }
  83362. if (force) {
  83363. this._cylinder.dispose();
  83364. }
  83365. else {
  83366. setTimeout(function () {
  83367. if (!_this._dataFetched) {
  83368. _this._cylinder.dispose();
  83369. }
  83370. }, 0);
  83371. }
  83372. };
  83373. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83374. if (impostor.mass === 0) {
  83375. return null;
  83376. }
  83377. if (!this._intersectsWithCylinder(impostor)) {
  83378. return null;
  83379. }
  83380. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83381. return null;
  83382. }
  83383. var impostorObjectCenter = impostor.getObjectCenter();
  83384. 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)
  83385. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  83386. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  83387. var hit = ray.intersectsMesh(impostor.object);
  83388. var contactPoint = hit.pickedPoint;
  83389. if (!contactPoint) {
  83390. return null;
  83391. }
  83392. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  83393. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  83394. var directionToOrigin = contactPoint.normalize();
  83395. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83396. directionToOrigin = directionToOrigin.negate();
  83397. }
  83398. // TODO: find a more physically based solution
  83399. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83400. var forceX = directionToOrigin.x * this._strength / 8;
  83401. var forceY = directionToOrigin.y * this._updraftMultiplier;
  83402. var forceZ = directionToOrigin.z * this._strength / 8;
  83403. }
  83404. else {
  83405. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  83406. var forceY = this._originTop.y * this._updraftMultiplier;
  83407. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  83408. }
  83409. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  83410. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  83411. return { force: force, contactPoint: impostorObjectCenter };
  83412. };
  83413. PhysicsVortexEvent.prototype._tick = function () {
  83414. var _this = this;
  83415. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83416. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83417. if (!impostorForceAndContactPoint) {
  83418. return;
  83419. }
  83420. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83421. });
  83422. };
  83423. /*** Helpers ***/
  83424. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  83425. if (!this._cylinder) {
  83426. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  83427. height: this._height,
  83428. diameter: this._radius * 2,
  83429. }, this._scene);
  83430. this._cylinder.isVisible = false;
  83431. }
  83432. };
  83433. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  83434. var impostorObject = impostor.object;
  83435. this._prepareCylinder();
  83436. this._cylinder.position = this._cylinderPosition;
  83437. return this._cylinder.intersectsMesh(impostorObject, true);
  83438. };
  83439. return PhysicsVortexEvent;
  83440. }());
  83441. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83442. /***** Enums *****/
  83443. /**
  83444. * The strenght of the force in correspondence to the distance of the affected object
  83445. */
  83446. var PhysicsRadialImpulseFalloff;
  83447. (function (PhysicsRadialImpulseFalloff) {
  83448. /** Defines that impulse is constant in strength across it's whole radius */
  83449. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83450. /** DEfines that impulse gets weaker if it's further from the origin */
  83451. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83452. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83453. /**
  83454. * The strenght of the force in correspondence to the distance of the affected object
  83455. */
  83456. var PhysicsUpdraftMode;
  83457. (function (PhysicsUpdraftMode) {
  83458. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83459. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83460. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83461. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83462. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83463. })(BABYLON || (BABYLON = {}));
  83464. //# sourceMappingURL=babylon.physicsHelper.js.map
  83465. var BABYLON;
  83466. (function (BABYLON) {
  83467. var CannonJSPlugin = /** @class */ (function () {
  83468. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83469. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83470. if (iterations === void 0) { iterations = 10; }
  83471. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83472. this.name = "CannonJSPlugin";
  83473. this._physicsMaterials = new Array();
  83474. this._fixedTimeStep = 1 / 60;
  83475. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83476. this.BJSCANNON = CANNON;
  83477. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83478. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83479. this._tmpPosition = BABYLON.Vector3.Zero();
  83480. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83481. this._tmpUnityRotation = new BABYLON.Quaternion();
  83482. if (!this.isSupported()) {
  83483. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83484. return;
  83485. }
  83486. this._extendNamespace();
  83487. this.world = new this.BJSCANNON.World();
  83488. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83489. this.world.solver.iterations = iterations;
  83490. }
  83491. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83492. this.world.gravity.copy(gravity);
  83493. };
  83494. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83495. this._fixedTimeStep = timeStep;
  83496. };
  83497. CannonJSPlugin.prototype.getTimeStep = function () {
  83498. return this._fixedTimeStep;
  83499. };
  83500. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83501. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83502. };
  83503. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83504. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83505. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83506. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83507. };
  83508. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83509. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83510. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83511. impostor.physicsBody.applyForce(impulse, worldPoint);
  83512. };
  83513. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83514. //parent-child relationship. Does this impostor has a parent impostor?
  83515. if (impostor.parent) {
  83516. if (impostor.physicsBody) {
  83517. this.removePhysicsBody(impostor);
  83518. //TODO is that needed?
  83519. impostor.forceUpdate();
  83520. }
  83521. return;
  83522. }
  83523. //should a new body be created for this impostor?
  83524. if (impostor.isBodyInitRequired()) {
  83525. var shape = this._createShape(impostor);
  83526. //unregister events, if body is being changed
  83527. var oldBody = impostor.physicsBody;
  83528. if (oldBody) {
  83529. this.removePhysicsBody(impostor);
  83530. }
  83531. //create the body and material
  83532. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83533. var bodyCreationObject = {
  83534. mass: impostor.getParam("mass"),
  83535. material: material
  83536. };
  83537. // A simple extend, in case native options were used.
  83538. var nativeOptions = impostor.getParam("nativeOptions");
  83539. for (var key in nativeOptions) {
  83540. if (nativeOptions.hasOwnProperty(key)) {
  83541. bodyCreationObject[key] = nativeOptions[key];
  83542. }
  83543. }
  83544. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83545. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83546. this.world.addEventListener("preStep", impostor.beforeStep);
  83547. this.world.addEventListener("postStep", impostor.afterStep);
  83548. impostor.physicsBody.addShape(shape);
  83549. this.world.add(impostor.physicsBody);
  83550. //try to keep the body moving in the right direction by taking old properties.
  83551. //Should be tested!
  83552. if (oldBody) {
  83553. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83554. impostor.physicsBody[param].copy(oldBody[param]);
  83555. });
  83556. }
  83557. this._processChildMeshes(impostor);
  83558. }
  83559. //now update the body's transformation
  83560. this._updatePhysicsBodyTransformation(impostor);
  83561. };
  83562. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83563. var _this = this;
  83564. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83565. var currentRotation = mainImpostor.object.rotationQuaternion;
  83566. if (meshChildren.length) {
  83567. var processMesh = function (localPosition, mesh) {
  83568. if (!currentRotation || !mesh.rotationQuaternion) {
  83569. return;
  83570. }
  83571. var childImpostor = mesh.getPhysicsImpostor();
  83572. if (childImpostor) {
  83573. var parent = childImpostor.parent;
  83574. if (parent !== mainImpostor) {
  83575. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83576. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83577. if (childImpostor.physicsBody) {
  83578. _this.removePhysicsBody(childImpostor);
  83579. childImpostor.physicsBody = null;
  83580. }
  83581. childImpostor.parent = mainImpostor;
  83582. childImpostor.resetUpdateFlags();
  83583. 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));
  83584. //Add the mass of the children.
  83585. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83586. }
  83587. }
  83588. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83589. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83590. };
  83591. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83592. }
  83593. };
  83594. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83595. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83596. this.world.removeEventListener("preStep", impostor.beforeStep);
  83597. this.world.removeEventListener("postStep", impostor.afterStep);
  83598. this.world.remove(impostor.physicsBody);
  83599. };
  83600. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83601. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83602. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83603. if (!mainBody || !connectedBody) {
  83604. return;
  83605. }
  83606. var constraint;
  83607. var jointData = impostorJoint.joint.jointData;
  83608. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83609. var constraintData = {
  83610. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83611. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83612. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83613. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83614. maxForce: jointData.nativeParams.maxForce,
  83615. collideConnected: !!jointData.collision
  83616. };
  83617. switch (impostorJoint.joint.type) {
  83618. case BABYLON.PhysicsJoint.HingeJoint:
  83619. case BABYLON.PhysicsJoint.Hinge2Joint:
  83620. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83621. break;
  83622. case BABYLON.PhysicsJoint.DistanceJoint:
  83623. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83624. break;
  83625. case BABYLON.PhysicsJoint.SpringJoint:
  83626. var springData = jointData;
  83627. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83628. restLength: springData.length,
  83629. stiffness: springData.stiffness,
  83630. damping: springData.damping,
  83631. localAnchorA: constraintData.pivotA,
  83632. localAnchorB: constraintData.pivotB
  83633. });
  83634. break;
  83635. case BABYLON.PhysicsJoint.LockJoint:
  83636. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83637. break;
  83638. case BABYLON.PhysicsJoint.PointToPointJoint:
  83639. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83640. default:
  83641. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83642. break;
  83643. }
  83644. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83645. constraint.collideConnected = !!jointData.collision;
  83646. impostorJoint.joint.physicsJoint = constraint;
  83647. //don't add spring as constraint, as it is not one.
  83648. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83649. this.world.addConstraint(constraint);
  83650. }
  83651. else {
  83652. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83653. constraint.applyForce();
  83654. });
  83655. }
  83656. };
  83657. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83658. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83659. };
  83660. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83661. var index;
  83662. var mat;
  83663. for (index = 0; index < this._physicsMaterials.length; index++) {
  83664. mat = this._physicsMaterials[index];
  83665. if (mat.friction === friction && mat.restitution === restitution) {
  83666. return mat;
  83667. }
  83668. }
  83669. var currentMat = new this.BJSCANNON.Material(name);
  83670. currentMat.friction = friction;
  83671. currentMat.restitution = restitution;
  83672. this._physicsMaterials.push(currentMat);
  83673. return currentMat;
  83674. };
  83675. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83676. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83677. };
  83678. CannonJSPlugin.prototype._createShape = function (impostor) {
  83679. var object = impostor.object;
  83680. var returnValue;
  83681. var extendSize = impostor.getObjectExtendSize();
  83682. switch (impostor.type) {
  83683. case BABYLON.PhysicsImpostor.SphereImpostor:
  83684. var radiusX = extendSize.x;
  83685. var radiusY = extendSize.y;
  83686. var radiusZ = extendSize.z;
  83687. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83688. break;
  83689. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83690. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83691. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83692. break;
  83693. case BABYLON.PhysicsImpostor.BoxImpostor:
  83694. var box = extendSize.scale(0.5);
  83695. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83696. break;
  83697. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83698. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83699. returnValue = new this.BJSCANNON.Plane();
  83700. break;
  83701. case BABYLON.PhysicsImpostor.MeshImpostor:
  83702. // should transform the vertex data to world coordinates!!
  83703. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83704. var rawFaces = object.getIndices ? object.getIndices() : [];
  83705. if (!rawVerts)
  83706. return;
  83707. // get only scale! so the object could transform correctly.
  83708. var oldPosition = object.position.clone();
  83709. var oldRotation = object.rotation && object.rotation.clone();
  83710. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83711. object.position.copyFromFloats(0, 0, 0);
  83712. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83713. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83714. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83715. var transform = object.computeWorldMatrix(true);
  83716. // convert rawVerts to object space
  83717. var temp = new Array();
  83718. var index;
  83719. for (index = 0; index < rawVerts.length; index += 3) {
  83720. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83721. }
  83722. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83723. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83724. //now set back the transformation!
  83725. object.position.copyFrom(oldPosition);
  83726. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83727. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83728. break;
  83729. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83730. var oldPosition2 = object.position.clone();
  83731. var oldRotation2 = object.rotation && object.rotation.clone();
  83732. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83733. object.position.copyFromFloats(0, 0, 0);
  83734. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83735. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83736. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83737. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83738. returnValue = this._createHeightmap(object);
  83739. object.position.copyFrom(oldPosition2);
  83740. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83741. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83742. object.computeWorldMatrix(true);
  83743. break;
  83744. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83745. returnValue = new this.BJSCANNON.Particle();
  83746. break;
  83747. }
  83748. return returnValue;
  83749. };
  83750. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83751. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83752. var transform = object.computeWorldMatrix(true);
  83753. // convert rawVerts to object space
  83754. var temp = new Array();
  83755. var index;
  83756. for (index = 0; index < pos.length; index += 3) {
  83757. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83758. }
  83759. pos = temp;
  83760. var matrix = new Array();
  83761. //For now pointDepth will not be used and will be automatically calculated.
  83762. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83763. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83764. var boundingInfo = object.getBoundingInfo();
  83765. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83766. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83767. var elementSize = dim * 2 / arraySize;
  83768. for (var i = 0; i < pos.length; i = i + 3) {
  83769. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83770. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83771. var y = -pos[i + 2] + minY;
  83772. if (!matrix[x]) {
  83773. matrix[x] = [];
  83774. }
  83775. if (!matrix[x][z]) {
  83776. matrix[x][z] = y;
  83777. }
  83778. matrix[x][z] = Math.max(y, matrix[x][z]);
  83779. }
  83780. for (var x = 0; x <= arraySize; ++x) {
  83781. if (!matrix[x]) {
  83782. var loc = 1;
  83783. while (!matrix[(x + loc) % arraySize]) {
  83784. loc++;
  83785. }
  83786. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83787. //console.log("missing x", x);
  83788. }
  83789. for (var z = 0; z <= arraySize; ++z) {
  83790. if (!matrix[x][z]) {
  83791. var loc = 1;
  83792. var newValue;
  83793. while (newValue === undefined) {
  83794. newValue = matrix[x][(z + loc++) % arraySize];
  83795. }
  83796. matrix[x][z] = newValue;
  83797. }
  83798. }
  83799. }
  83800. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83801. elementSize: elementSize
  83802. });
  83803. //For future reference, needed for body transformation
  83804. shape.minY = minY;
  83805. return shape;
  83806. };
  83807. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83808. var object = impostor.object;
  83809. //make sure it is updated...
  83810. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83811. // The delta between the mesh position and the mesh bounding box center
  83812. var bInfo = object.getBoundingInfo();
  83813. if (!bInfo)
  83814. return;
  83815. var center = impostor.getObjectCenter();
  83816. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83817. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83818. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83819. this._tmpPosition.copyFrom(center);
  83820. var quaternion = object.rotationQuaternion;
  83821. if (!quaternion) {
  83822. return;
  83823. }
  83824. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83825. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83826. //-90 DEG in X, precalculated
  83827. quaternion = quaternion.multiply(this._minus90X);
  83828. //Invert! (Precalculated, 90 deg in X)
  83829. //No need to clone. this will never change.
  83830. impostor.setDeltaRotation(this._plus90X);
  83831. }
  83832. //If it is a heightfield, if should be centered.
  83833. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83834. var mesh = object;
  83835. var boundingInfo = mesh.getBoundingInfo();
  83836. //calculate the correct body position:
  83837. var rotationQuaternion = mesh.rotationQuaternion;
  83838. mesh.rotationQuaternion = this._tmpUnityRotation;
  83839. mesh.computeWorldMatrix(true);
  83840. //get original center with no rotation
  83841. var c = center.clone();
  83842. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83843. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83844. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83845. mesh.setPreTransformMatrix(p);
  83846. mesh.computeWorldMatrix(true);
  83847. //calculate the translation
  83848. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83849. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83850. //add it inverted to the delta
  83851. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83852. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83853. //rotation is back
  83854. mesh.rotationQuaternion = rotationQuaternion;
  83855. mesh.setPreTransformMatrix(oldPivot);
  83856. mesh.computeWorldMatrix(true);
  83857. }
  83858. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83859. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83860. //this._tmpPosition.copyFrom(object.position);
  83861. }
  83862. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83863. //Now update the impostor object
  83864. impostor.physicsBody.position.copy(this._tmpPosition);
  83865. impostor.physicsBody.quaternion.copy(quaternion);
  83866. };
  83867. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83868. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83869. if (impostor.object.rotationQuaternion) {
  83870. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83871. }
  83872. };
  83873. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83874. impostor.physicsBody.position.copy(newPosition);
  83875. impostor.physicsBody.quaternion.copy(newRotation);
  83876. };
  83877. CannonJSPlugin.prototype.isSupported = function () {
  83878. return this.BJSCANNON !== undefined;
  83879. };
  83880. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83881. impostor.physicsBody.velocity.copy(velocity);
  83882. };
  83883. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83884. impostor.physicsBody.angularVelocity.copy(velocity);
  83885. };
  83886. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83887. var v = impostor.physicsBody.velocity;
  83888. if (!v) {
  83889. return null;
  83890. }
  83891. return new BABYLON.Vector3(v.x, v.y, v.z);
  83892. };
  83893. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83894. var v = impostor.physicsBody.angularVelocity;
  83895. if (!v) {
  83896. return null;
  83897. }
  83898. return new BABYLON.Vector3(v.x, v.y, v.z);
  83899. };
  83900. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83901. impostor.physicsBody.mass = mass;
  83902. impostor.physicsBody.updateMassProperties();
  83903. };
  83904. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83905. return impostor.physicsBody.mass;
  83906. };
  83907. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83908. return impostor.physicsBody.material.friction;
  83909. };
  83910. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83911. impostor.physicsBody.material.friction = friction;
  83912. };
  83913. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83914. return impostor.physicsBody.material.restitution;
  83915. };
  83916. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83917. impostor.physicsBody.material.restitution = restitution;
  83918. };
  83919. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83920. impostor.physicsBody.sleep();
  83921. };
  83922. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83923. impostor.physicsBody.wakeUp();
  83924. };
  83925. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83926. joint.physicsJoint.distance = maxDistance;
  83927. };
  83928. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83929. // if (!motorIndex) {
  83930. // joint.physicsJoint.enableMotor();
  83931. // }
  83932. // }
  83933. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83934. // if (!motorIndex) {
  83935. // joint.physicsJoint.disableMotor();
  83936. // }
  83937. // }
  83938. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83939. if (!motorIndex) {
  83940. joint.physicsJoint.enableMotor();
  83941. joint.physicsJoint.setMotorSpeed(speed);
  83942. if (maxForce) {
  83943. this.setLimit(joint, maxForce);
  83944. }
  83945. }
  83946. };
  83947. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83948. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83949. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83950. };
  83951. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83952. var body = impostor.physicsBody;
  83953. mesh.position.x = body.position.x;
  83954. mesh.position.y = body.position.y;
  83955. mesh.position.z = body.position.z;
  83956. if (mesh.rotationQuaternion) {
  83957. mesh.rotationQuaternion.x = body.quaternion.x;
  83958. mesh.rotationQuaternion.y = body.quaternion.y;
  83959. mesh.rotationQuaternion.z = body.quaternion.z;
  83960. mesh.rotationQuaternion.w = body.quaternion.w;
  83961. }
  83962. };
  83963. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83964. var shape = impostor.physicsBody.shapes[0];
  83965. return shape.boundingSphereRadius;
  83966. };
  83967. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83968. var shape = impostor.physicsBody.shapes[0];
  83969. result.x = shape.halfExtents.x * 2;
  83970. result.y = shape.halfExtents.y * 2;
  83971. result.z = shape.halfExtents.z * 2;
  83972. };
  83973. CannonJSPlugin.prototype.dispose = function () {
  83974. };
  83975. CannonJSPlugin.prototype._extendNamespace = function () {
  83976. //this will force cannon to execute at least one step when using interpolation
  83977. var step_tmp1 = new this.BJSCANNON.Vec3();
  83978. var Engine = this.BJSCANNON;
  83979. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83980. maxSubSteps = maxSubSteps || 10;
  83981. timeSinceLastCalled = timeSinceLastCalled || 0;
  83982. if (timeSinceLastCalled === 0) {
  83983. this.internalStep(dt);
  83984. this.time += dt;
  83985. }
  83986. else {
  83987. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83988. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83989. var t0 = performance.now();
  83990. for (var i = 0; i !== internalSteps; i++) {
  83991. this.internalStep(dt);
  83992. if (performance.now() - t0 > dt * 1000) {
  83993. break;
  83994. }
  83995. }
  83996. this.time += timeSinceLastCalled;
  83997. var h = this.time % dt;
  83998. var h_div_dt = h / dt;
  83999. var interpvelo = step_tmp1;
  84000. var bodies = this.bodies;
  84001. for (var j = 0; j !== bodies.length; j++) {
  84002. var b = bodies[j];
  84003. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  84004. b.position.vsub(b.previousPosition, interpvelo);
  84005. interpvelo.scale(h_div_dt, interpvelo);
  84006. b.position.vadd(interpvelo, b.interpolatedPosition);
  84007. }
  84008. else {
  84009. b.interpolatedPosition.copy(b.position);
  84010. b.interpolatedQuaternion.copy(b.quaternion);
  84011. }
  84012. }
  84013. }
  84014. };
  84015. };
  84016. return CannonJSPlugin;
  84017. }());
  84018. BABYLON.CannonJSPlugin = CannonJSPlugin;
  84019. })(BABYLON || (BABYLON = {}));
  84020. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  84021. var BABYLON;
  84022. (function (BABYLON) {
  84023. var OimoJSPlugin = /** @class */ (function () {
  84024. function OimoJSPlugin(iterations) {
  84025. this.name = "OimoJSPlugin";
  84026. this._tmpImpostorsArray = [];
  84027. this._tmpPositionVector = BABYLON.Vector3.Zero();
  84028. this.BJSOIMO = OIMO;
  84029. this.world = new this.BJSOIMO.World({
  84030. iterations: iterations
  84031. });
  84032. this.world.clear();
  84033. }
  84034. OimoJSPlugin.prototype.setGravity = function (gravity) {
  84035. this.world.gravity.copy(gravity);
  84036. };
  84037. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  84038. this.world.timeStep = timeStep;
  84039. };
  84040. OimoJSPlugin.prototype.getTimeStep = function () {
  84041. return this.world.timeStep;
  84042. };
  84043. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  84044. var _this = this;
  84045. impostors.forEach(function (impostor) {
  84046. impostor.beforeStep();
  84047. });
  84048. this.world.step();
  84049. impostors.forEach(function (impostor) {
  84050. impostor.afterStep();
  84051. //update the ordered impostors array
  84052. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  84053. });
  84054. //check for collisions
  84055. var contact = this.world.contacts;
  84056. while (contact !== null) {
  84057. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  84058. contact = contact.next;
  84059. continue;
  84060. }
  84061. //is this body colliding with any other? get the impostor
  84062. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  84063. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  84064. if (!mainImpostor || !collidingImpostor) {
  84065. contact = contact.next;
  84066. continue;
  84067. }
  84068. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  84069. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  84070. contact = contact.next;
  84071. }
  84072. };
  84073. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84074. var mass = impostor.physicsBody.mass;
  84075. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  84076. };
  84077. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84078. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  84079. this.applyImpulse(impostor, force, contactPoint);
  84080. };
  84081. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84082. var _this = this;
  84083. //parent-child relationship. Does this impostor has a parent impostor?
  84084. if (impostor.parent) {
  84085. if (impostor.physicsBody) {
  84086. this.removePhysicsBody(impostor);
  84087. //TODO is that needed?
  84088. impostor.forceUpdate();
  84089. }
  84090. return;
  84091. }
  84092. if (impostor.isBodyInitRequired()) {
  84093. var bodyConfig = {
  84094. name: impostor.uniqueId,
  84095. //Oimo must have mass, also for static objects.
  84096. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  84097. size: [],
  84098. type: [],
  84099. pos: [],
  84100. posShape: [],
  84101. rot: [],
  84102. rotShape: [],
  84103. move: impostor.getParam("mass") !== 0,
  84104. density: impostor.getParam("mass"),
  84105. friction: impostor.getParam("friction"),
  84106. restitution: impostor.getParam("restitution"),
  84107. //Supporting older versions of Oimo
  84108. world: this.world
  84109. };
  84110. var impostors = [impostor];
  84111. var addToArray = function (parent) {
  84112. if (!parent.getChildMeshes)
  84113. return;
  84114. parent.getChildMeshes().forEach(function (m) {
  84115. if (m.physicsImpostor) {
  84116. impostors.push(m.physicsImpostor);
  84117. //m.physicsImpostor._init();
  84118. }
  84119. });
  84120. };
  84121. addToArray(impostor.object);
  84122. var checkWithEpsilon_1 = function (value) {
  84123. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  84124. };
  84125. impostors.forEach(function (i) {
  84126. if (!i.object.rotationQuaternion) {
  84127. return;
  84128. }
  84129. //get the correct bounding box
  84130. var oldQuaternion = i.object.rotationQuaternion;
  84131. var rot = oldQuaternion.toEulerAngles();
  84132. var extendSize = i.getObjectExtendSize();
  84133. var radToDeg = 57.295779513082320876;
  84134. if (i === impostor) {
  84135. var center = impostor.getObjectCenter();
  84136. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  84137. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  84138. //Can also use Array.prototype.push.apply
  84139. bodyConfig.pos.push(center.x);
  84140. bodyConfig.pos.push(center.y);
  84141. bodyConfig.pos.push(center.z);
  84142. bodyConfig.posShape.push(0, 0, 0);
  84143. //tmp solution
  84144. bodyConfig.rot.push(rot.x * radToDeg);
  84145. bodyConfig.rot.push(rot.y * radToDeg);
  84146. bodyConfig.rot.push(rot.z * radToDeg);
  84147. bodyConfig.rotShape.push(0, 0, 0);
  84148. }
  84149. else {
  84150. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  84151. bodyConfig.posShape.push(localPosition.x);
  84152. bodyConfig.posShape.push(localPosition.y);
  84153. bodyConfig.posShape.push(localPosition.z);
  84154. bodyConfig.pos.push(0, 0, 0);
  84155. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  84156. bodyConfig.rot.push(0);
  84157. bodyConfig.rot.push(0);
  84158. bodyConfig.rot.push(0);
  84159. bodyConfig.rotShape.push(rot.x * radToDeg);
  84160. bodyConfig.rotShape.push(rot.y * radToDeg);
  84161. bodyConfig.rotShape.push(rot.z * radToDeg);
  84162. }
  84163. // register mesh
  84164. switch (i.type) {
  84165. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84166. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  84167. case BABYLON.PhysicsImpostor.SphereImpostor:
  84168. var radiusX = extendSize.x;
  84169. var radiusY = extendSize.y;
  84170. var radiusZ = extendSize.z;
  84171. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  84172. bodyConfig.type.push('sphere');
  84173. //due to the way oimo works with compounds, add 3 times
  84174. bodyConfig.size.push(size);
  84175. bodyConfig.size.push(size);
  84176. bodyConfig.size.push(size);
  84177. break;
  84178. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84179. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  84180. var sizeY = checkWithEpsilon_1(extendSize.y);
  84181. bodyConfig.type.push('cylinder');
  84182. bodyConfig.size.push(sizeX);
  84183. bodyConfig.size.push(sizeY);
  84184. //due to the way oimo works with compounds, add one more value.
  84185. bodyConfig.size.push(sizeY);
  84186. break;
  84187. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84188. case BABYLON.PhysicsImpostor.BoxImpostor:
  84189. default:
  84190. var sizeX = checkWithEpsilon_1(extendSize.x);
  84191. var sizeY = checkWithEpsilon_1(extendSize.y);
  84192. var sizeZ = checkWithEpsilon_1(extendSize.z);
  84193. bodyConfig.type.push('box');
  84194. //if (i === impostor) {
  84195. bodyConfig.size.push(sizeX);
  84196. bodyConfig.size.push(sizeY);
  84197. bodyConfig.size.push(sizeZ);
  84198. //} else {
  84199. // bodyConfig.size.push(0,0,0);
  84200. //}
  84201. break;
  84202. }
  84203. //actually not needed, but hey...
  84204. i.object.rotationQuaternion = oldQuaternion;
  84205. });
  84206. impostor.physicsBody = this.world.add(bodyConfig);
  84207. }
  84208. else {
  84209. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  84210. }
  84211. impostor.setDeltaPosition(this._tmpPositionVector);
  84212. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  84213. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  84214. };
  84215. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84216. //impostor.physicsBody.dispose();
  84217. //Same as : (older oimo versions)
  84218. this.world.removeRigidBody(impostor.physicsBody);
  84219. };
  84220. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84221. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84222. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84223. if (!mainBody || !connectedBody) {
  84224. return;
  84225. }
  84226. var jointData = impostorJoint.joint.jointData;
  84227. var options = jointData.nativeParams || {};
  84228. var type;
  84229. var nativeJointData = {
  84230. body1: mainBody,
  84231. body2: connectedBody,
  84232. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  84233. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  84234. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  84235. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  84236. min: options.min,
  84237. max: options.max,
  84238. collision: options.collision || jointData.collision,
  84239. spring: options.spring,
  84240. //supporting older version of Oimo
  84241. world: this.world
  84242. };
  84243. switch (impostorJoint.joint.type) {
  84244. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84245. type = "jointBall";
  84246. break;
  84247. case BABYLON.PhysicsJoint.SpringJoint:
  84248. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  84249. var springData = jointData;
  84250. nativeJointData.min = springData.length || nativeJointData.min;
  84251. //Max should also be set, just make sure it is at least min
  84252. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  84253. case BABYLON.PhysicsJoint.DistanceJoint:
  84254. type = "jointDistance";
  84255. nativeJointData.max = jointData.maxDistance;
  84256. break;
  84257. case BABYLON.PhysicsJoint.PrismaticJoint:
  84258. type = "jointPrisme";
  84259. break;
  84260. case BABYLON.PhysicsJoint.SliderJoint:
  84261. type = "jointSlide";
  84262. break;
  84263. case BABYLON.PhysicsJoint.WheelJoint:
  84264. type = "jointWheel";
  84265. break;
  84266. case BABYLON.PhysicsJoint.HingeJoint:
  84267. default:
  84268. type = "jointHinge";
  84269. break;
  84270. }
  84271. nativeJointData.type = type;
  84272. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  84273. };
  84274. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84275. //Bug in Oimo prevents us from disposing a joint in the playground
  84276. //joint.joint.physicsJoint.dispose();
  84277. //So we will bruteforce it!
  84278. try {
  84279. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  84280. }
  84281. catch (e) {
  84282. BABYLON.Tools.Warn(e);
  84283. }
  84284. };
  84285. OimoJSPlugin.prototype.isSupported = function () {
  84286. return this.BJSOIMO !== undefined;
  84287. };
  84288. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84289. if (!impostor.physicsBody.sleeping) {
  84290. //TODO check that
  84291. /*if (impostor.physicsBody.shapes.next) {
  84292. var parentShape = this._getLastShape(impostor.physicsBody);
  84293. impostor.object.position.copyFrom(parentShape.position);
  84294. console.log(parentShape.position);
  84295. } else {*/
  84296. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  84297. //}
  84298. if (impostor.object.rotationQuaternion) {
  84299. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  84300. }
  84301. }
  84302. };
  84303. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84304. var body = impostor.physicsBody;
  84305. body.position.copy(newPosition);
  84306. body.orientation.copy(newRotation);
  84307. body.syncShapes();
  84308. body.awake();
  84309. };
  84310. /*private _getLastShape(body: any): any {
  84311. var lastShape = body.shapes;
  84312. while (lastShape.next) {
  84313. lastShape = lastShape.next;
  84314. }
  84315. return lastShape;
  84316. }*/
  84317. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84318. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  84319. };
  84320. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84321. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  84322. };
  84323. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84324. var v = impostor.physicsBody.linearVelocity;
  84325. if (!v) {
  84326. return null;
  84327. }
  84328. return new BABYLON.Vector3(v.x, v.y, v.z);
  84329. };
  84330. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84331. var v = impostor.physicsBody.angularVelocity;
  84332. if (!v) {
  84333. return null;
  84334. }
  84335. return new BABYLON.Vector3(v.x, v.y, v.z);
  84336. };
  84337. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84338. var staticBody = mass === 0;
  84339. //this will actually set the body's density and not its mass.
  84340. //But this is how oimo treats the mass variable.
  84341. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  84342. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  84343. };
  84344. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  84345. return impostor.physicsBody.shapes.density;
  84346. };
  84347. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  84348. return impostor.physicsBody.shapes.friction;
  84349. };
  84350. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84351. impostor.physicsBody.shapes.friction = friction;
  84352. };
  84353. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84354. return impostor.physicsBody.shapes.restitution;
  84355. };
  84356. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84357. impostor.physicsBody.shapes.restitution = restitution;
  84358. };
  84359. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  84360. impostor.physicsBody.sleep();
  84361. };
  84362. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  84363. impostor.physicsBody.awake();
  84364. };
  84365. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84366. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  84367. if (minDistance !== void 0) {
  84368. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  84369. }
  84370. };
  84371. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84372. //TODO separate rotational and transational motors.
  84373. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84374. if (motor) {
  84375. motor.setMotor(speed, maxForce);
  84376. }
  84377. };
  84378. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  84379. //TODO separate rotational and transational motors.
  84380. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84381. if (motor) {
  84382. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  84383. }
  84384. };
  84385. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84386. var body = impostor.physicsBody;
  84387. mesh.position.x = body.position.x;
  84388. mesh.position.y = body.position.y;
  84389. mesh.position.z = body.position.z;
  84390. if (mesh.rotationQuaternion) {
  84391. mesh.rotationQuaternion.x = body.orientation.x;
  84392. mesh.rotationQuaternion.y = body.orientation.y;
  84393. mesh.rotationQuaternion.z = body.orientation.z;
  84394. mesh.rotationQuaternion.w = body.orientation.s;
  84395. }
  84396. };
  84397. OimoJSPlugin.prototype.getRadius = function (impostor) {
  84398. return impostor.physicsBody.shapes.radius;
  84399. };
  84400. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84401. var shape = impostor.physicsBody.shapes;
  84402. result.x = shape.halfWidth * 2;
  84403. result.y = shape.halfHeight * 2;
  84404. result.z = shape.halfDepth * 2;
  84405. };
  84406. OimoJSPlugin.prototype.dispose = function () {
  84407. this.world.clear();
  84408. };
  84409. return OimoJSPlugin;
  84410. }());
  84411. BABYLON.OimoJSPlugin = OimoJSPlugin;
  84412. })(BABYLON || (BABYLON = {}));
  84413. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  84414. var BABYLON;
  84415. (function (BABYLON) {
  84416. /*
  84417. * Based on jsTGALoader - Javascript loader for TGA file
  84418. * By Vincent Thibault
  84419. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  84420. */
  84421. var TGATools = /** @class */ (function () {
  84422. function TGATools() {
  84423. }
  84424. TGATools.GetTGAHeader = function (data) {
  84425. var offset = 0;
  84426. var header = {
  84427. id_length: data[offset++],
  84428. colormap_type: data[offset++],
  84429. image_type: data[offset++],
  84430. colormap_index: data[offset++] | data[offset++] << 8,
  84431. colormap_length: data[offset++] | data[offset++] << 8,
  84432. colormap_size: data[offset++],
  84433. origin: [
  84434. data[offset++] | data[offset++] << 8,
  84435. data[offset++] | data[offset++] << 8
  84436. ],
  84437. width: data[offset++] | data[offset++] << 8,
  84438. height: data[offset++] | data[offset++] << 8,
  84439. pixel_size: data[offset++],
  84440. flags: data[offset++]
  84441. };
  84442. return header;
  84443. };
  84444. TGATools.UploadContent = function (gl, data) {
  84445. // Not enough data to contain header ?
  84446. if (data.length < 19) {
  84447. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84448. return;
  84449. }
  84450. // Read Header
  84451. var offset = 18;
  84452. var header = TGATools.GetTGAHeader(data);
  84453. // Assume it's a valid Targa file.
  84454. if (header.id_length + offset > data.length) {
  84455. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84456. return;
  84457. }
  84458. // Skip not needed data
  84459. offset += header.id_length;
  84460. var use_rle = false;
  84461. var use_pal = false;
  84462. var use_grey = false;
  84463. // Get some informations.
  84464. switch (header.image_type) {
  84465. case TGATools._TYPE_RLE_INDEXED:
  84466. use_rle = true;
  84467. case TGATools._TYPE_INDEXED:
  84468. use_pal = true;
  84469. break;
  84470. case TGATools._TYPE_RLE_RGB:
  84471. use_rle = true;
  84472. case TGATools._TYPE_RGB:
  84473. // use_rgb = true;
  84474. break;
  84475. case TGATools._TYPE_RLE_GREY:
  84476. use_rle = true;
  84477. case TGATools._TYPE_GREY:
  84478. use_grey = true;
  84479. break;
  84480. }
  84481. var pixel_data;
  84482. // var numAlphaBits = header.flags & 0xf;
  84483. var pixel_size = header.pixel_size >> 3;
  84484. var pixel_total = header.width * header.height * pixel_size;
  84485. // Read palettes
  84486. var palettes;
  84487. if (use_pal) {
  84488. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84489. }
  84490. // Read LRE
  84491. if (use_rle) {
  84492. pixel_data = new Uint8Array(pixel_total);
  84493. var c, count, i;
  84494. var localOffset = 0;
  84495. var pixels = new Uint8Array(pixel_size);
  84496. while (offset < pixel_total && localOffset < pixel_total) {
  84497. c = data[offset++];
  84498. count = (c & 0x7f) + 1;
  84499. // RLE pixels
  84500. if (c & 0x80) {
  84501. // Bind pixel tmp array
  84502. for (i = 0; i < pixel_size; ++i) {
  84503. pixels[i] = data[offset++];
  84504. }
  84505. // Copy pixel array
  84506. for (i = 0; i < count; ++i) {
  84507. pixel_data.set(pixels, localOffset + i * pixel_size);
  84508. }
  84509. localOffset += pixel_size * count;
  84510. }
  84511. // Raw pixels
  84512. else {
  84513. count *= pixel_size;
  84514. for (i = 0; i < count; ++i) {
  84515. pixel_data[localOffset + i] = data[offset++];
  84516. }
  84517. localOffset += count;
  84518. }
  84519. }
  84520. }
  84521. // RAW Pixels
  84522. else {
  84523. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84524. }
  84525. // Load to texture
  84526. var x_start, y_start, x_step, y_step, y_end, x_end;
  84527. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84528. default:
  84529. case TGATools._ORIGIN_UL:
  84530. x_start = 0;
  84531. x_step = 1;
  84532. x_end = header.width;
  84533. y_start = 0;
  84534. y_step = 1;
  84535. y_end = header.height;
  84536. break;
  84537. case TGATools._ORIGIN_BL:
  84538. x_start = 0;
  84539. x_step = 1;
  84540. x_end = header.width;
  84541. y_start = header.height - 1;
  84542. y_step = -1;
  84543. y_end = -1;
  84544. break;
  84545. case TGATools._ORIGIN_UR:
  84546. x_start = header.width - 1;
  84547. x_step = -1;
  84548. x_end = -1;
  84549. y_start = 0;
  84550. y_step = 1;
  84551. y_end = header.height;
  84552. break;
  84553. case TGATools._ORIGIN_BR:
  84554. x_start = header.width - 1;
  84555. x_step = -1;
  84556. x_end = -1;
  84557. y_start = header.height - 1;
  84558. y_step = -1;
  84559. y_end = -1;
  84560. break;
  84561. }
  84562. // Load the specify method
  84563. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84564. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84565. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84566. };
  84567. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84568. var image = pixel_data, colormap = palettes;
  84569. var width = header.width, height = header.height;
  84570. var color, i = 0, x, y;
  84571. var imageData = new Uint8Array(width * height * 4);
  84572. for (y = y_start; y !== y_end; y += y_step) {
  84573. for (x = x_start; x !== x_end; x += x_step, i++) {
  84574. color = image[i];
  84575. imageData[(x + width * y) * 4 + 3] = 255;
  84576. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84577. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84578. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84579. }
  84580. }
  84581. return imageData;
  84582. };
  84583. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84584. var image = pixel_data;
  84585. var width = header.width, height = header.height;
  84586. var color, i = 0, x, y;
  84587. var imageData = new Uint8Array(width * height * 4);
  84588. for (y = y_start; y !== y_end; y += y_step) {
  84589. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84590. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84591. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84592. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84593. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84594. imageData[(x + width * y) * 4 + 0] = r;
  84595. imageData[(x + width * y) * 4 + 1] = g;
  84596. imageData[(x + width * y) * 4 + 2] = b;
  84597. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84598. }
  84599. }
  84600. return imageData;
  84601. };
  84602. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84603. var image = pixel_data;
  84604. var width = header.width, height = header.height;
  84605. var i = 0, x, y;
  84606. var imageData = new Uint8Array(width * height * 4);
  84607. for (y = y_start; y !== y_end; y += y_step) {
  84608. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84609. imageData[(x + width * y) * 4 + 3] = 255;
  84610. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84611. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84612. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84613. }
  84614. }
  84615. return imageData;
  84616. };
  84617. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84618. var image = pixel_data;
  84619. var width = header.width, height = header.height;
  84620. var i = 0, x, y;
  84621. var imageData = new Uint8Array(width * height * 4);
  84622. for (y = y_start; y !== y_end; y += y_step) {
  84623. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84624. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84625. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84626. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84627. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84628. }
  84629. }
  84630. return imageData;
  84631. };
  84632. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84633. var image = pixel_data;
  84634. var width = header.width, height = header.height;
  84635. var color, i = 0, x, y;
  84636. var imageData = new Uint8Array(width * height * 4);
  84637. for (y = y_start; y !== y_end; y += y_step) {
  84638. for (x = x_start; x !== x_end; x += x_step, i++) {
  84639. color = image[i];
  84640. imageData[(x + width * y) * 4 + 0] = color;
  84641. imageData[(x + width * y) * 4 + 1] = color;
  84642. imageData[(x + width * y) * 4 + 2] = color;
  84643. imageData[(x + width * y) * 4 + 3] = 255;
  84644. }
  84645. }
  84646. return imageData;
  84647. };
  84648. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84649. var image = pixel_data;
  84650. var width = header.width, height = header.height;
  84651. var i = 0, x, y;
  84652. var imageData = new Uint8Array(width * height * 4);
  84653. for (y = y_start; y !== y_end; y += y_step) {
  84654. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84655. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84656. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84657. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84658. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84659. }
  84660. }
  84661. return imageData;
  84662. };
  84663. //private static _TYPE_NO_DATA = 0;
  84664. TGATools._TYPE_INDEXED = 1;
  84665. TGATools._TYPE_RGB = 2;
  84666. TGATools._TYPE_GREY = 3;
  84667. TGATools._TYPE_RLE_INDEXED = 9;
  84668. TGATools._TYPE_RLE_RGB = 10;
  84669. TGATools._TYPE_RLE_GREY = 11;
  84670. TGATools._ORIGIN_MASK = 0x30;
  84671. TGATools._ORIGIN_SHIFT = 0x04;
  84672. TGATools._ORIGIN_BL = 0x00;
  84673. TGATools._ORIGIN_BR = 0x01;
  84674. TGATools._ORIGIN_UL = 0x02;
  84675. TGATools._ORIGIN_UR = 0x03;
  84676. return TGATools;
  84677. }());
  84678. BABYLON.TGATools = TGATools;
  84679. })(BABYLON || (BABYLON = {}));
  84680. //# sourceMappingURL=babylon.tga.js.map
  84681. var BABYLON;
  84682. (function (BABYLON) {
  84683. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84684. // All values and structures referenced from:
  84685. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84686. var DDS_MAGIC = 0x20534444;
  84687. var
  84688. //DDSD_CAPS = 0x1,
  84689. //DDSD_HEIGHT = 0x2,
  84690. //DDSD_WIDTH = 0x4,
  84691. //DDSD_PITCH = 0x8,
  84692. //DDSD_PIXELFORMAT = 0x1000,
  84693. DDSD_MIPMAPCOUNT = 0x20000;
  84694. //DDSD_LINEARSIZE = 0x80000,
  84695. //DDSD_DEPTH = 0x800000;
  84696. // var DDSCAPS_COMPLEX = 0x8,
  84697. // DDSCAPS_MIPMAP = 0x400000,
  84698. // DDSCAPS_TEXTURE = 0x1000;
  84699. var DDSCAPS2_CUBEMAP = 0x200;
  84700. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84701. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84702. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84703. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84704. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84705. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84706. // DDSCAPS2_VOLUME = 0x200000;
  84707. var
  84708. //DDPF_ALPHAPIXELS = 0x1,
  84709. //DDPF_ALPHA = 0x2,
  84710. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84711. //DDPF_YUV = 0x200,
  84712. DDPF_LUMINANCE = 0x20000;
  84713. function FourCCToInt32(value) {
  84714. return value.charCodeAt(0) +
  84715. (value.charCodeAt(1) << 8) +
  84716. (value.charCodeAt(2) << 16) +
  84717. (value.charCodeAt(3) << 24);
  84718. }
  84719. function Int32ToFourCC(value) {
  84720. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84721. }
  84722. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84723. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84724. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84725. var FOURCC_DX10 = FourCCToInt32("DX10");
  84726. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84727. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84728. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84729. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84730. var headerLengthInt = 31; // The header length in 32 bit ints
  84731. // Offsets into the header array
  84732. var off_magic = 0;
  84733. var off_size = 1;
  84734. var off_flags = 2;
  84735. var off_height = 3;
  84736. var off_width = 4;
  84737. var off_mipmapCount = 7;
  84738. var off_pfFlags = 20;
  84739. var off_pfFourCC = 21;
  84740. var off_RGBbpp = 22;
  84741. var off_RMask = 23;
  84742. var off_GMask = 24;
  84743. var off_BMask = 25;
  84744. var off_AMask = 26;
  84745. // var off_caps1 = 27;
  84746. var off_caps2 = 28;
  84747. // var off_caps3 = 29;
  84748. // var off_caps4 = 30;
  84749. var off_dxgiFormat = 32;
  84750. ;
  84751. var DDSTools = /** @class */ (function () {
  84752. function DDSTools() {
  84753. }
  84754. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84755. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84756. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84757. var mipmapCount = 1;
  84758. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84759. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84760. }
  84761. var fourCC = header[off_pfFourCC];
  84762. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84763. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84764. switch (fourCC) {
  84765. case FOURCC_D3DFMT_R16G16B16A16F:
  84766. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84767. break;
  84768. case FOURCC_D3DFMT_R32G32B32A32F:
  84769. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84770. break;
  84771. case FOURCC_DX10:
  84772. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84773. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84774. break;
  84775. }
  84776. }
  84777. return {
  84778. width: header[off_width],
  84779. height: header[off_height],
  84780. mipmapCount: mipmapCount,
  84781. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84782. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84783. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84784. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84785. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84786. dxgiFormat: dxgiFormat,
  84787. textureType: textureType
  84788. };
  84789. };
  84790. DDSTools._ToHalfFloat = function (value) {
  84791. if (!DDSTools._FloatView) {
  84792. DDSTools._FloatView = new Float32Array(1);
  84793. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84794. }
  84795. DDSTools._FloatView[0] = value;
  84796. var x = DDSTools._Int32View[0];
  84797. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84798. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84799. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84800. /* If zero, or denormal, or exponent underflows too much for a denormal
  84801. * half, return signed zero. */
  84802. if (e < 103) {
  84803. return bits;
  84804. }
  84805. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84806. if (e > 142) {
  84807. bits |= 0x7c00;
  84808. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84809. * not Inf, so make sure we set one mantissa bit too. */
  84810. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84811. return bits;
  84812. }
  84813. /* If exponent underflows but not too much, return a denormal */
  84814. if (e < 113) {
  84815. m |= 0x0800;
  84816. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84817. * to 1, which is OK. */
  84818. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84819. return bits;
  84820. }
  84821. bits |= ((e - 112) << 10) | (m >> 1);
  84822. bits += m & 1;
  84823. return bits;
  84824. };
  84825. DDSTools._FromHalfFloat = function (value) {
  84826. var s = (value & 0x8000) >> 15;
  84827. var e = (value & 0x7C00) >> 10;
  84828. var f = value & 0x03FF;
  84829. if (e === 0) {
  84830. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84831. }
  84832. else if (e == 0x1F) {
  84833. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84834. }
  84835. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84836. };
  84837. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84838. var destArray = new Float32Array(dataLength);
  84839. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84840. var index = 0;
  84841. for (var y = 0; y < height; y++) {
  84842. for (var x = 0; x < width; x++) {
  84843. var srcPos = (x + y * width) * 4;
  84844. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84845. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84846. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84847. if (DDSTools.StoreLODInAlphaChannel) {
  84848. destArray[index + 3] = lod;
  84849. }
  84850. else {
  84851. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84852. }
  84853. index += 4;
  84854. }
  84855. }
  84856. return destArray;
  84857. };
  84858. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84859. if (DDSTools.StoreLODInAlphaChannel) {
  84860. var destArray = new Uint16Array(dataLength);
  84861. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84862. var index = 0;
  84863. for (var y = 0; y < height; y++) {
  84864. for (var x = 0; x < width; x++) {
  84865. var srcPos = (x + y * width) * 4;
  84866. destArray[index] = srcData[srcPos];
  84867. destArray[index + 1] = srcData[srcPos + 1];
  84868. destArray[index + 2] = srcData[srcPos + 2];
  84869. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84870. index += 4;
  84871. }
  84872. }
  84873. return destArray;
  84874. }
  84875. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84876. };
  84877. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84878. if (DDSTools.StoreLODInAlphaChannel) {
  84879. var destArray = new Float32Array(dataLength);
  84880. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84881. var index = 0;
  84882. for (var y = 0; y < height; y++) {
  84883. for (var x = 0; x < width; x++) {
  84884. var srcPos = (x + y * width) * 4;
  84885. destArray[index] = srcData[srcPos];
  84886. destArray[index + 1] = srcData[srcPos + 1];
  84887. destArray[index + 2] = srcData[srcPos + 2];
  84888. destArray[index + 3] = lod;
  84889. index += 4;
  84890. }
  84891. }
  84892. return destArray;
  84893. }
  84894. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84895. };
  84896. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84897. var destArray = new Uint8Array(dataLength);
  84898. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84899. var index = 0;
  84900. for (var y = 0; y < height; y++) {
  84901. for (var x = 0; x < width; x++) {
  84902. var srcPos = (x + y * width) * 4;
  84903. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84904. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84905. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84906. if (DDSTools.StoreLODInAlphaChannel) {
  84907. destArray[index + 3] = lod;
  84908. }
  84909. else {
  84910. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84911. }
  84912. index += 4;
  84913. }
  84914. }
  84915. return destArray;
  84916. };
  84917. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84918. var destArray = new Uint8Array(dataLength);
  84919. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84920. var index = 0;
  84921. for (var y = 0; y < height; y++) {
  84922. for (var x = 0; x < width; x++) {
  84923. var srcPos = (x + y * width) * 4;
  84924. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84925. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84926. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84927. if (DDSTools.StoreLODInAlphaChannel) {
  84928. destArray[index + 3] = lod;
  84929. }
  84930. else {
  84931. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84932. }
  84933. index += 4;
  84934. }
  84935. }
  84936. return destArray;
  84937. };
  84938. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84939. var byteArray = new Uint8Array(dataLength);
  84940. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84941. var index = 0;
  84942. for (var y = 0; y < height; y++) {
  84943. for (var x = 0; x < width; x++) {
  84944. var srcPos = (x + y * width) * 4;
  84945. byteArray[index] = srcData[srcPos + rOffset];
  84946. byteArray[index + 1] = srcData[srcPos + gOffset];
  84947. byteArray[index + 2] = srcData[srcPos + bOffset];
  84948. byteArray[index + 3] = srcData[srcPos + aOffset];
  84949. index += 4;
  84950. }
  84951. }
  84952. return byteArray;
  84953. };
  84954. DDSTools._ExtractLongWordOrder = function (value) {
  84955. if (value === 0 || value === 255 || value === -16777216) {
  84956. return 0;
  84957. }
  84958. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84959. };
  84960. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84961. var byteArray = new Uint8Array(dataLength);
  84962. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84963. var index = 0;
  84964. for (var y = 0; y < height; y++) {
  84965. for (var x = 0; x < width; x++) {
  84966. var srcPos = (x + y * width) * 3;
  84967. byteArray[index] = srcData[srcPos + rOffset];
  84968. byteArray[index + 1] = srcData[srcPos + gOffset];
  84969. byteArray[index + 2] = srcData[srcPos + bOffset];
  84970. index += 3;
  84971. }
  84972. }
  84973. return byteArray;
  84974. };
  84975. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84976. var byteArray = new Uint8Array(dataLength);
  84977. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84978. var index = 0;
  84979. for (var y = 0; y < height; y++) {
  84980. for (var x = 0; x < width; x++) {
  84981. var srcPos = (x + y * width);
  84982. byteArray[index] = srcData[srcPos];
  84983. index++;
  84984. }
  84985. }
  84986. return byteArray;
  84987. };
  84988. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84989. if (lodIndex === void 0) { lodIndex = -1; }
  84990. var sphericalPolynomialFaces = null;
  84991. if (info.sphericalPolynomial) {
  84992. sphericalPolynomialFaces = new Array();
  84993. }
  84994. var ext = engine.getCaps().s3tc;
  84995. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84996. var fourCC, width, height, dataLength = 0, dataOffset;
  84997. var byteArray, mipmapCount, mip;
  84998. var internalFormat = 0;
  84999. var format = 0;
  85000. var blockBytes = 1;
  85001. if (header[off_magic] !== DDS_MAGIC) {
  85002. BABYLON.Tools.Error("Invalid magic number in DDS header");
  85003. return;
  85004. }
  85005. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  85006. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  85007. return;
  85008. }
  85009. if (info.isCompressed && !ext) {
  85010. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  85011. return;
  85012. }
  85013. var bpp = header[off_RGBbpp];
  85014. dataOffset = header[off_size] + 4;
  85015. var computeFormats = false;
  85016. if (info.isFourCC) {
  85017. fourCC = header[off_pfFourCC];
  85018. switch (fourCC) {
  85019. case FOURCC_DXT1:
  85020. blockBytes = 8;
  85021. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  85022. break;
  85023. case FOURCC_DXT3:
  85024. blockBytes = 16;
  85025. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  85026. break;
  85027. case FOURCC_DXT5:
  85028. blockBytes = 16;
  85029. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  85030. break;
  85031. case FOURCC_D3DFMT_R16G16B16A16F:
  85032. computeFormats = true;
  85033. break;
  85034. case FOURCC_D3DFMT_R32G32B32A32F:
  85035. computeFormats = true;
  85036. break;
  85037. case FOURCC_DX10:
  85038. // There is an additionnal header so dataOffset need to be changed
  85039. dataOffset += 5 * 4; // 5 uints
  85040. var supported = false;
  85041. switch (info.dxgiFormat) {
  85042. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  85043. computeFormats = true;
  85044. supported = true;
  85045. break;
  85046. case DXGI_FORMAT_B8G8R8X8_UNORM:
  85047. info.isRGB = true;
  85048. info.isFourCC = false;
  85049. bpp = 32;
  85050. supported = true;
  85051. break;
  85052. }
  85053. if (supported) {
  85054. break;
  85055. }
  85056. default:
  85057. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  85058. return;
  85059. }
  85060. }
  85061. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  85062. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  85063. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  85064. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  85065. if (computeFormats) {
  85066. format = engine._getWebGLTextureType(info.textureType);
  85067. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85068. }
  85069. mipmapCount = 1;
  85070. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  85071. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85072. }
  85073. for (var face = 0; face < faces; face++) {
  85074. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  85075. width = header[off_width];
  85076. height = header[off_height];
  85077. for (mip = 0; mip < mipmapCount; ++mip) {
  85078. if (lodIndex === -1 || lodIndex === mip) {
  85079. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  85080. var i = (lodIndex === -1) ? mip : 0;
  85081. if (!info.isCompressed && info.isFourCC) {
  85082. dataLength = width * height * 4;
  85083. var floatArray = null;
  85084. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  85085. if (bpp === 128) {
  85086. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85087. if (sphericalPolynomialFaces && i == 0) {
  85088. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85089. }
  85090. }
  85091. else if (bpp === 64) {
  85092. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85093. if (sphericalPolynomialFaces && i == 0) {
  85094. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85095. }
  85096. }
  85097. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85098. format = engine._getWebGLTextureType(info.textureType);
  85099. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85100. }
  85101. else {
  85102. if (bpp === 128) {
  85103. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85104. if (sphericalPolynomialFaces && i == 0) {
  85105. sphericalPolynomialFaces.push(floatArray);
  85106. }
  85107. }
  85108. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  85109. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85110. if (sphericalPolynomialFaces && i == 0) {
  85111. sphericalPolynomialFaces.push(floatArray);
  85112. }
  85113. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85114. format = engine._getWebGLTextureType(info.textureType);
  85115. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85116. }
  85117. else { // 64
  85118. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85119. if (sphericalPolynomialFaces && i == 0) {
  85120. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85121. }
  85122. }
  85123. }
  85124. if (floatArray) {
  85125. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  85126. }
  85127. }
  85128. else if (info.isRGB) {
  85129. if (bpp === 24) {
  85130. dataLength = width * height * 3;
  85131. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  85132. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  85133. }
  85134. else { // 32
  85135. dataLength = width * height * 4;
  85136. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  85137. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  85138. }
  85139. }
  85140. else if (info.isLuminance) {
  85141. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  85142. var unpaddedRowSize = width;
  85143. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  85144. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  85145. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  85146. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  85147. }
  85148. else {
  85149. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  85150. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  85151. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  85152. }
  85153. }
  85154. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  85155. width *= 0.5;
  85156. height *= 0.5;
  85157. width = Math.max(1.0, width);
  85158. height = Math.max(1.0, height);
  85159. }
  85160. if (currentFace !== undefined) {
  85161. // Loading a single face
  85162. break;
  85163. }
  85164. }
  85165. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  85166. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  85167. size: header[off_width],
  85168. right: sphericalPolynomialFaces[0],
  85169. left: sphericalPolynomialFaces[1],
  85170. up: sphericalPolynomialFaces[2],
  85171. down: sphericalPolynomialFaces[3],
  85172. front: sphericalPolynomialFaces[4],
  85173. back: sphericalPolynomialFaces[5],
  85174. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  85175. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  85176. gammaSpace: false,
  85177. });
  85178. }
  85179. else {
  85180. info.sphericalPolynomial = undefined;
  85181. }
  85182. };
  85183. DDSTools.StoreLODInAlphaChannel = false;
  85184. return DDSTools;
  85185. }());
  85186. BABYLON.DDSTools = DDSTools;
  85187. })(BABYLON || (BABYLON = {}));
  85188. //# sourceMappingURL=babylon.dds.js.map
  85189. var BABYLON;
  85190. (function (BABYLON) {
  85191. /**
  85192. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  85193. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  85194. */
  85195. var KhronosTextureContainer = /** @class */ (function () {
  85196. /**
  85197. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  85198. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  85199. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  85200. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  85201. */
  85202. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  85203. this.arrayBuffer = arrayBuffer;
  85204. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  85205. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  85206. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  85207. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  85208. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  85209. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  85210. BABYLON.Tools.Error("texture missing KTX identifier");
  85211. return;
  85212. }
  85213. // load the reset of the header in native 32 bit int
  85214. var header = new Int32Array(this.arrayBuffer, 12, 13);
  85215. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  85216. var oppositeEndianess = header[0] === 0x01020304;
  85217. // read all the header elements in order they exist in the file, without modification (sans endainness)
  85218. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  85219. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  85220. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  85221. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  85222. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  85223. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  85224. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  85225. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  85226. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  85227. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  85228. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  85229. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  85230. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  85231. if (this.glType !== 0) {
  85232. BABYLON.Tools.Error("only compressed formats currently supported");
  85233. return;
  85234. }
  85235. else {
  85236. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  85237. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  85238. }
  85239. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  85240. BABYLON.Tools.Error("only 2D textures currently supported");
  85241. return;
  85242. }
  85243. if (this.numberOfArrayElements !== 0) {
  85244. BABYLON.Tools.Error("texture arrays not currently supported");
  85245. return;
  85246. }
  85247. if (this.numberOfFaces !== facesExpected) {
  85248. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  85249. return;
  85250. }
  85251. // we now have a completely validated file, so could use existence of loadType as success
  85252. // would need to make this more elaborate & adjust checks above to support more than one load type
  85253. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  85254. }
  85255. // not as fast hardware based, but will probably never need to use
  85256. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  85257. return ((val & 0xFF) << 24)
  85258. | ((val & 0xFF00) << 8)
  85259. | ((val >> 8) & 0xFF00)
  85260. | ((val >> 24) & 0xFF);
  85261. };
  85262. /**
  85263. * It is assumed that the texture has already been created & is currently bound
  85264. */
  85265. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  85266. switch (this.loadType) {
  85267. case KhronosTextureContainer.COMPRESSED_2D:
  85268. this._upload2DCompressedLevels(gl, loadMipmaps);
  85269. break;
  85270. case KhronosTextureContainer.TEX_2D:
  85271. case KhronosTextureContainer.COMPRESSED_3D:
  85272. case KhronosTextureContainer.TEX_3D:
  85273. }
  85274. };
  85275. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  85276. // initialize width & height for level 1
  85277. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  85278. var width = this.pixelWidth;
  85279. var height = this.pixelHeight;
  85280. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  85281. for (var level = 0; level < mipmapCount; level++) {
  85282. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  85283. for (var face = 0; face < this.numberOfFaces; face++) {
  85284. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  85285. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  85286. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  85287. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  85288. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  85289. }
  85290. width = Math.max(1.0, width * 0.5);
  85291. height = Math.max(1.0, height * 0.5);
  85292. }
  85293. };
  85294. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  85295. // load types
  85296. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  85297. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  85298. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  85299. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  85300. return KhronosTextureContainer;
  85301. }());
  85302. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  85303. })(BABYLON || (BABYLON = {}));
  85304. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  85305. var BABYLON;
  85306. (function (BABYLON) {
  85307. var Debug;
  85308. (function (Debug) {
  85309. /**
  85310. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  85311. */
  85312. var SkeletonViewer = /** @class */ (function () {
  85313. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  85314. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  85315. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  85316. this.skeleton = skeleton;
  85317. this.mesh = mesh;
  85318. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  85319. this.renderingGroupId = renderingGroupId;
  85320. this.color = BABYLON.Color3.White();
  85321. this._debugLines = new Array();
  85322. this._isEnabled = false;
  85323. this._scene = scene;
  85324. this.update();
  85325. this._renderFunction = this.update.bind(this);
  85326. }
  85327. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  85328. get: function () {
  85329. return this._isEnabled;
  85330. },
  85331. set: function (value) {
  85332. if (this._isEnabled === value) {
  85333. return;
  85334. }
  85335. this._isEnabled = value;
  85336. if (value) {
  85337. this._scene.registerBeforeRender(this._renderFunction);
  85338. }
  85339. else {
  85340. this._scene.unregisterBeforeRender(this._renderFunction);
  85341. }
  85342. },
  85343. enumerable: true,
  85344. configurable: true
  85345. });
  85346. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  85347. if (x === void 0) { x = 0; }
  85348. if (y === void 0) { y = 0; }
  85349. if (z === void 0) { z = 0; }
  85350. var tmat = BABYLON.Tmp.Matrix[0];
  85351. var parentBone = bone.getParent();
  85352. tmat.copyFrom(bone.getLocalMatrix());
  85353. if (x !== 0 || y !== 0 || z !== 0) {
  85354. var tmat2 = BABYLON.Tmp.Matrix[1];
  85355. BABYLON.Matrix.IdentityToRef(tmat2);
  85356. tmat2.m[12] = x;
  85357. tmat2.m[13] = y;
  85358. tmat2.m[14] = z;
  85359. tmat2.multiplyToRef(tmat, tmat);
  85360. }
  85361. if (parentBone) {
  85362. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  85363. }
  85364. tmat.multiplyToRef(meshMat, tmat);
  85365. position.x = tmat.m[12];
  85366. position.y = tmat.m[13];
  85367. position.z = tmat.m[14];
  85368. };
  85369. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  85370. var len = bones.length;
  85371. var meshPos = this.mesh.position;
  85372. for (var i = 0; i < len; i++) {
  85373. var bone = bones[i];
  85374. var points = this._debugLines[i];
  85375. if (!points) {
  85376. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85377. this._debugLines[i] = points;
  85378. }
  85379. this._getBonePosition(points[0], bone, meshMat);
  85380. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  85381. points[0].subtractInPlace(meshPos);
  85382. points[1].subtractInPlace(meshPos);
  85383. }
  85384. };
  85385. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  85386. var len = bones.length;
  85387. var boneNum = 0;
  85388. var meshPos = this.mesh.position;
  85389. for (var i = len - 1; i >= 0; i--) {
  85390. var childBone = bones[i];
  85391. var parentBone = childBone.getParent();
  85392. if (!parentBone) {
  85393. continue;
  85394. }
  85395. var points = this._debugLines[boneNum];
  85396. if (!points) {
  85397. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85398. this._debugLines[boneNum] = points;
  85399. }
  85400. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  85401. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  85402. points[0].subtractInPlace(meshPos);
  85403. points[1].subtractInPlace(meshPos);
  85404. boneNum++;
  85405. }
  85406. };
  85407. SkeletonViewer.prototype.update = function () {
  85408. if (this.autoUpdateBonesMatrices) {
  85409. this.skeleton.computeAbsoluteTransforms();
  85410. }
  85411. if (this.skeleton.bones[0].length === undefined) {
  85412. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85413. }
  85414. else {
  85415. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85416. }
  85417. if (!this._debugMesh) {
  85418. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  85419. this._debugMesh.renderingGroupId = this.renderingGroupId;
  85420. }
  85421. else {
  85422. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  85423. }
  85424. this._debugMesh.position.copyFrom(this.mesh.position);
  85425. this._debugMesh.color = this.color;
  85426. };
  85427. SkeletonViewer.prototype.dispose = function () {
  85428. if (this._debugMesh) {
  85429. this.isEnabled = false;
  85430. this._debugMesh.dispose();
  85431. this._debugMesh = null;
  85432. }
  85433. };
  85434. return SkeletonViewer;
  85435. }());
  85436. Debug.SkeletonViewer = SkeletonViewer;
  85437. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85438. })(BABYLON || (BABYLON = {}));
  85439. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85440. /**
  85441. * Module Debug contains the (visual) components to debug a scene correctly
  85442. */
  85443. var BABYLON;
  85444. (function (BABYLON) {
  85445. var Debug;
  85446. (function (Debug) {
  85447. /**
  85448. * The Axes viewer will show 3 axes in a specific point in space
  85449. */
  85450. var AxesViewer = /** @class */ (function () {
  85451. function AxesViewer(scene, scaleLines) {
  85452. if (scaleLines === void 0) { scaleLines = 1; }
  85453. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85454. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85455. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85456. this.scaleLines = 1;
  85457. this.scaleLines = scaleLines;
  85458. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85459. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85460. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85461. this._xmesh.renderingGroupId = 2;
  85462. this._ymesh.renderingGroupId = 2;
  85463. this._zmesh.renderingGroupId = 2;
  85464. this._xmesh.material.checkReadyOnlyOnce = true;
  85465. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85466. this._ymesh.material.checkReadyOnlyOnce = true;
  85467. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85468. this._zmesh.material.checkReadyOnlyOnce = true;
  85469. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85470. this.scene = scene;
  85471. }
  85472. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85473. var scaleLines = this.scaleLines;
  85474. if (this._xmesh) {
  85475. this._xmesh.position.copyFrom(position);
  85476. }
  85477. if (this._ymesh) {
  85478. this._ymesh.position.copyFrom(position);
  85479. }
  85480. if (this._zmesh) {
  85481. this._zmesh.position.copyFrom(position);
  85482. }
  85483. var point2 = this._xline[1];
  85484. point2.x = xaxis.x * scaleLines;
  85485. point2.y = xaxis.y * scaleLines;
  85486. point2.z = xaxis.z * scaleLines;
  85487. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85488. point2 = this._yline[1];
  85489. point2.x = yaxis.x * scaleLines;
  85490. point2.y = yaxis.y * scaleLines;
  85491. point2.z = yaxis.z * scaleLines;
  85492. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85493. point2 = this._zline[1];
  85494. point2.x = zaxis.x * scaleLines;
  85495. point2.y = zaxis.y * scaleLines;
  85496. point2.z = zaxis.z * scaleLines;
  85497. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85498. };
  85499. AxesViewer.prototype.dispose = function () {
  85500. if (this._xmesh) {
  85501. this._xmesh.dispose();
  85502. }
  85503. if (this._ymesh) {
  85504. this._ymesh.dispose();
  85505. }
  85506. if (this._zmesh) {
  85507. this._zmesh.dispose();
  85508. }
  85509. this._xmesh = null;
  85510. this._ymesh = null;
  85511. this._zmesh = null;
  85512. this.scene = null;
  85513. };
  85514. return AxesViewer;
  85515. }());
  85516. Debug.AxesViewer = AxesViewer;
  85517. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85518. })(BABYLON || (BABYLON = {}));
  85519. //# sourceMappingURL=babylon.axesViewer.js.map
  85520. var BABYLON;
  85521. (function (BABYLON) {
  85522. var Debug;
  85523. (function (Debug) {
  85524. /**
  85525. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85526. */
  85527. var BoneAxesViewer = /** @class */ (function (_super) {
  85528. __extends(BoneAxesViewer, _super);
  85529. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85530. if (scaleLines === void 0) { scaleLines = 1; }
  85531. var _this = _super.call(this, scene, scaleLines) || this;
  85532. _this.pos = BABYLON.Vector3.Zero();
  85533. _this.xaxis = BABYLON.Vector3.Zero();
  85534. _this.yaxis = BABYLON.Vector3.Zero();
  85535. _this.zaxis = BABYLON.Vector3.Zero();
  85536. _this.mesh = mesh;
  85537. _this.bone = bone;
  85538. return _this;
  85539. }
  85540. BoneAxesViewer.prototype.update = function () {
  85541. if (!this.mesh || !this.bone) {
  85542. return;
  85543. }
  85544. var bone = this.bone;
  85545. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85546. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85547. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85548. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85549. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85550. };
  85551. BoneAxesViewer.prototype.dispose = function () {
  85552. if (this.mesh) {
  85553. this.mesh = null;
  85554. this.bone = null;
  85555. _super.prototype.dispose.call(this);
  85556. }
  85557. };
  85558. return BoneAxesViewer;
  85559. }(Debug.AxesViewer));
  85560. Debug.BoneAxesViewer = BoneAxesViewer;
  85561. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85562. })(BABYLON || (BABYLON = {}));
  85563. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85564. var BABYLON;
  85565. (function (BABYLON) {
  85566. var RayHelper = /** @class */ (function () {
  85567. function RayHelper(ray) {
  85568. this.ray = ray;
  85569. }
  85570. RayHelper.CreateAndShow = function (ray, scene, color) {
  85571. var helper = new RayHelper(ray);
  85572. helper.show(scene, color);
  85573. return helper;
  85574. };
  85575. RayHelper.prototype.show = function (scene, color) {
  85576. if (!this._renderFunction && this.ray) {
  85577. var ray = this.ray;
  85578. this._renderFunction = this._render.bind(this);
  85579. this._scene = scene;
  85580. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85581. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85582. if (this._renderFunction) {
  85583. this._scene.registerBeforeRender(this._renderFunction);
  85584. }
  85585. }
  85586. if (color && this._renderLine) {
  85587. this._renderLine.color.copyFrom(color);
  85588. }
  85589. };
  85590. RayHelper.prototype.hide = function () {
  85591. if (this._renderFunction && this._scene) {
  85592. this._scene.unregisterBeforeRender(this._renderFunction);
  85593. this._scene = null;
  85594. this._renderFunction = null;
  85595. if (this._renderLine) {
  85596. this._renderLine.dispose();
  85597. this._renderLine = null;
  85598. }
  85599. this._renderPoints = [];
  85600. }
  85601. };
  85602. RayHelper.prototype._render = function () {
  85603. var ray = this.ray;
  85604. if (!ray) {
  85605. return;
  85606. }
  85607. var point = this._renderPoints[1];
  85608. var len = Math.min(ray.length, 1000000);
  85609. point.copyFrom(ray.direction);
  85610. point.scaleInPlace(len);
  85611. point.addInPlace(ray.origin);
  85612. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85613. };
  85614. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85615. this._attachedToMesh = mesh;
  85616. var ray = this.ray;
  85617. if (!ray) {
  85618. return;
  85619. }
  85620. if (!ray.direction) {
  85621. ray.direction = BABYLON.Vector3.Zero();
  85622. }
  85623. if (!ray.origin) {
  85624. ray.origin = BABYLON.Vector3.Zero();
  85625. }
  85626. if (length) {
  85627. ray.length = length;
  85628. }
  85629. if (!meshSpaceOrigin) {
  85630. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85631. }
  85632. if (!meshSpaceDirection) {
  85633. // -1 so that this will work with Mesh.lookAt
  85634. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85635. }
  85636. if (!this._meshSpaceDirection) {
  85637. this._meshSpaceDirection = meshSpaceDirection.clone();
  85638. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85639. }
  85640. else {
  85641. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85642. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85643. }
  85644. if (!this._updateToMeshFunction) {
  85645. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85646. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85647. }
  85648. this._updateToMesh();
  85649. };
  85650. RayHelper.prototype.detachFromMesh = function () {
  85651. if (this._attachedToMesh) {
  85652. if (this._updateToMeshFunction) {
  85653. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85654. }
  85655. this._attachedToMesh = null;
  85656. this._updateToMeshFunction = null;
  85657. }
  85658. };
  85659. RayHelper.prototype._updateToMesh = function () {
  85660. var ray = this.ray;
  85661. if (!this._attachedToMesh || !ray) {
  85662. return;
  85663. }
  85664. if (this._attachedToMesh._isDisposed) {
  85665. this.detachFromMesh();
  85666. return;
  85667. }
  85668. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85669. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85670. };
  85671. RayHelper.prototype.dispose = function () {
  85672. this.hide();
  85673. this.detachFromMesh();
  85674. this.ray = null;
  85675. };
  85676. return RayHelper;
  85677. }());
  85678. BABYLON.RayHelper = RayHelper;
  85679. })(BABYLON || (BABYLON = {}));
  85680. //# sourceMappingURL=babylon.rayHelper.js.map
  85681. var BABYLON;
  85682. (function (BABYLON) {
  85683. // load the inspector using require, if not present in the global namespace.
  85684. var DebugLayer = /** @class */ (function () {
  85685. function DebugLayer(scene) {
  85686. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85687. this._scene = scene;
  85688. // load inspector using require, if it doesn't exist on the global namespace.
  85689. }
  85690. /** Creates the inspector window. */
  85691. DebugLayer.prototype._createInspector = function (config) {
  85692. if (config === void 0) { config = {}; }
  85693. var popup = config.popup || false;
  85694. var initialTab = config.initialTab || 0;
  85695. var parentElement = config.parentElement || null;
  85696. if (!this._inspector) {
  85697. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85698. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85699. } // else nothing to do,; instance is already existing
  85700. };
  85701. DebugLayer.prototype.isVisible = function () {
  85702. if (!this._inspector) {
  85703. return false;
  85704. }
  85705. return true;
  85706. };
  85707. DebugLayer.prototype.hide = function () {
  85708. if (this._inspector) {
  85709. try {
  85710. this._inspector.dispose();
  85711. }
  85712. catch (e) {
  85713. // If the inspector has been removed directly from the inspector tool
  85714. }
  85715. this._inspector = null;
  85716. }
  85717. };
  85718. DebugLayer.prototype.show = function (config) {
  85719. if (config === void 0) { config = {}; }
  85720. if (typeof this.BJSINSPECTOR == 'undefined') {
  85721. // Load inspector and add it to the DOM
  85722. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85723. }
  85724. else {
  85725. // Otherwise creates the inspector
  85726. this._createInspector(config);
  85727. }
  85728. };
  85729. /**
  85730. * Gets the active tab
  85731. * @return the index of the active tab or -1 if the inspector is hidden
  85732. */
  85733. DebugLayer.prototype.getActiveTab = function () {
  85734. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  85735. };
  85736. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85737. return DebugLayer;
  85738. }());
  85739. BABYLON.DebugLayer = DebugLayer;
  85740. })(BABYLON || (BABYLON = {}));
  85741. //# sourceMappingURL=babylon.debugLayer.js.map
  85742. var BABYLON;
  85743. (function (BABYLON) {
  85744. var Debug;
  85745. (function (Debug) {
  85746. /**
  85747. * Used to show the physics impostor around the specific mesh.
  85748. */
  85749. var PhysicsViewer = /** @class */ (function () {
  85750. function PhysicsViewer(scene) {
  85751. this._impostors = [];
  85752. this._meshes = [];
  85753. this._numMeshes = 0;
  85754. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85755. var physicEngine = this._scene.getPhysicsEngine();
  85756. if (physicEngine) {
  85757. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85758. }
  85759. }
  85760. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85761. var plugin = this._physicsEnginePlugin;
  85762. for (var i = 0; i < this._numMeshes; i++) {
  85763. var impostor = this._impostors[i];
  85764. if (!impostor) {
  85765. continue;
  85766. }
  85767. if (impostor.isDisposed) {
  85768. this.hideImpostor(this._impostors[i--]);
  85769. }
  85770. else {
  85771. var mesh = this._meshes[i];
  85772. if (mesh && plugin) {
  85773. plugin.syncMeshWithImpostor(mesh, impostor);
  85774. }
  85775. }
  85776. }
  85777. };
  85778. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85779. if (!this._scene) {
  85780. return;
  85781. }
  85782. for (var i = 0; i < this._numMeshes; i++) {
  85783. if (this._impostors[i] == impostor) {
  85784. return;
  85785. }
  85786. }
  85787. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85788. if (debugMesh) {
  85789. this._impostors[this._numMeshes] = impostor;
  85790. this._meshes[this._numMeshes] = debugMesh;
  85791. if (this._numMeshes === 0) {
  85792. this._renderFunction = this._updateDebugMeshes.bind(this);
  85793. this._scene.registerBeforeRender(this._renderFunction);
  85794. }
  85795. this._numMeshes++;
  85796. }
  85797. };
  85798. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85799. if (!impostor || !this._scene) {
  85800. return;
  85801. }
  85802. var removed = false;
  85803. for (var i = 0; i < this._numMeshes; i++) {
  85804. if (this._impostors[i] == impostor) {
  85805. var mesh = this._meshes[i];
  85806. if (!mesh) {
  85807. continue;
  85808. }
  85809. this._scene.removeMesh(mesh);
  85810. mesh.dispose();
  85811. this._numMeshes--;
  85812. if (this._numMeshes > 0) {
  85813. this._meshes[i] = this._meshes[this._numMeshes];
  85814. this._impostors[i] = this._impostors[this._numMeshes];
  85815. this._meshes[this._numMeshes] = null;
  85816. this._impostors[this._numMeshes] = null;
  85817. }
  85818. else {
  85819. this._meshes[0] = null;
  85820. this._impostors[0] = null;
  85821. }
  85822. removed = true;
  85823. break;
  85824. }
  85825. }
  85826. if (removed && this._numMeshes === 0) {
  85827. this._scene.unregisterBeforeRender(this._renderFunction);
  85828. }
  85829. };
  85830. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85831. if (!this._debugMaterial) {
  85832. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85833. this._debugMaterial.wireframe = true;
  85834. }
  85835. return this._debugMaterial;
  85836. };
  85837. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85838. if (!this._debugBoxMesh) {
  85839. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85840. this._debugBoxMesh.renderingGroupId = 1;
  85841. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85842. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85843. scene.removeMesh(this._debugBoxMesh);
  85844. }
  85845. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85846. };
  85847. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85848. if (!this._debugSphereMesh) {
  85849. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85850. this._debugSphereMesh.renderingGroupId = 1;
  85851. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85852. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85853. scene.removeMesh(this._debugSphereMesh);
  85854. }
  85855. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85856. };
  85857. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85858. var mesh = null;
  85859. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85860. mesh = this._getDebugBoxMesh(scene);
  85861. impostor.getBoxSizeToRef(mesh.scaling);
  85862. }
  85863. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85864. mesh = this._getDebugSphereMesh(scene);
  85865. var radius = impostor.getRadius();
  85866. mesh.scaling.x = radius * 2;
  85867. mesh.scaling.y = radius * 2;
  85868. mesh.scaling.z = radius * 2;
  85869. }
  85870. return mesh;
  85871. };
  85872. PhysicsViewer.prototype.dispose = function () {
  85873. for (var i = 0; i < this._numMeshes; i++) {
  85874. this.hideImpostor(this._impostors[i]);
  85875. }
  85876. if (this._debugBoxMesh) {
  85877. this._debugBoxMesh.dispose();
  85878. }
  85879. if (this._debugSphereMesh) {
  85880. this._debugSphereMesh.dispose();
  85881. }
  85882. if (this._debugMaterial) {
  85883. this._debugMaterial.dispose();
  85884. }
  85885. this._impostors.length = 0;
  85886. this._scene = null;
  85887. this._physicsEnginePlugin = null;
  85888. };
  85889. return PhysicsViewer;
  85890. }());
  85891. Debug.PhysicsViewer = PhysicsViewer;
  85892. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85893. })(BABYLON || (BABYLON = {}));
  85894. //# sourceMappingURL=babylon.physicsViewer.js.map
  85895. var BABYLON;
  85896. (function (BABYLON) {
  85897. var BoundingBoxRenderer = /** @class */ (function () {
  85898. function BoundingBoxRenderer(scene) {
  85899. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85900. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85901. this.showBackLines = true;
  85902. this.renderList = new BABYLON.SmartArray(32);
  85903. this._vertexBuffers = {};
  85904. this._scene = scene;
  85905. }
  85906. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85907. if (this._colorShader) {
  85908. return;
  85909. }
  85910. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85911. attributes: [BABYLON.VertexBuffer.PositionKind],
  85912. uniforms: ["world", "viewProjection", "color"]
  85913. });
  85914. var engine = this._scene.getEngine();
  85915. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85916. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85917. this._createIndexBuffer();
  85918. };
  85919. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85920. var engine = this._scene.getEngine();
  85921. 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]);
  85922. };
  85923. BoundingBoxRenderer.prototype._rebuild = function () {
  85924. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85925. if (vb) {
  85926. vb._rebuild();
  85927. }
  85928. this._createIndexBuffer();
  85929. };
  85930. BoundingBoxRenderer.prototype.reset = function () {
  85931. this.renderList.reset();
  85932. };
  85933. BoundingBoxRenderer.prototype.render = function () {
  85934. if (this.renderList.length === 0) {
  85935. return;
  85936. }
  85937. this._prepareRessources();
  85938. if (!this._colorShader.isReady()) {
  85939. return;
  85940. }
  85941. var engine = this._scene.getEngine();
  85942. engine.setDepthWrite(false);
  85943. this._colorShader._preBind();
  85944. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85945. var boundingBox = this.renderList.data[boundingBoxIndex];
  85946. var min = boundingBox.minimum;
  85947. var max = boundingBox.maximum;
  85948. var diff = max.subtract(min);
  85949. var median = min.add(diff.scale(0.5));
  85950. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85951. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85952. .multiply(boundingBox.getWorldMatrix());
  85953. // VBOs
  85954. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85955. if (this.showBackLines) {
  85956. // Back
  85957. engine.setDepthFunctionToGreaterOrEqual();
  85958. this._scene.resetCachedMaterial();
  85959. this._colorShader.setColor4("color", this.backColor.toColor4());
  85960. this._colorShader.bind(worldMatrix);
  85961. // Draw order
  85962. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85963. }
  85964. // Front
  85965. engine.setDepthFunctionToLess();
  85966. this._scene.resetCachedMaterial();
  85967. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85968. this._colorShader.bind(worldMatrix);
  85969. // Draw order
  85970. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85971. }
  85972. this._colorShader.unbind();
  85973. engine.setDepthFunctionToLessOrEqual();
  85974. engine.setDepthWrite(true);
  85975. };
  85976. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85977. this._prepareRessources();
  85978. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85979. return;
  85980. }
  85981. var engine = this._scene.getEngine();
  85982. engine.setDepthWrite(false);
  85983. engine.setColorWrite(false);
  85984. this._colorShader._preBind();
  85985. var boundingBox = mesh._boundingInfo.boundingBox;
  85986. var min = boundingBox.minimum;
  85987. var max = boundingBox.maximum;
  85988. var diff = max.subtract(min);
  85989. var median = min.add(diff.scale(0.5));
  85990. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85991. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85992. .multiply(boundingBox.getWorldMatrix());
  85993. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85994. engine.setDepthFunctionToLess();
  85995. this._scene.resetCachedMaterial();
  85996. this._colorShader.bind(worldMatrix);
  85997. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85998. this._colorShader.unbind();
  85999. engine.setDepthFunctionToLessOrEqual();
  86000. engine.setDepthWrite(true);
  86001. engine.setColorWrite(true);
  86002. };
  86003. BoundingBoxRenderer.prototype.dispose = function () {
  86004. if (!this._colorShader) {
  86005. return;
  86006. }
  86007. this.renderList.dispose();
  86008. this._colorShader.dispose();
  86009. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86010. if (buffer) {
  86011. buffer.dispose();
  86012. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86013. }
  86014. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86015. };
  86016. return BoundingBoxRenderer;
  86017. }());
  86018. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  86019. })(BABYLON || (BABYLON = {}));
  86020. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  86021. var BABYLON;
  86022. (function (BABYLON) {
  86023. /**
  86024. * Renders a layer on top of an existing scene
  86025. */
  86026. var UtilityLayerRenderer = /** @class */ (function () {
  86027. /**
  86028. * Instantiates a UtilityLayerRenderer
  86029. * @param originalScene the original scene that will be rendered on top of
  86030. */
  86031. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  86032. var _this = this;
  86033. this.originalScene = originalScene;
  86034. /**
  86035. * If the utility layer should automatically be rendered on top of existing scene
  86036. */
  86037. this.shouldRender = true;
  86038. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  86039. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  86040. originalScene.getEngine().scenes.pop();
  86041. // Render directly on top of existing scene without clearing
  86042. this.utilityLayerScene.clearColor = new BABYLON.Color4(0, 0, 0, 0);
  86043. this.utilityLayerScene.autoClear = false;
  86044. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  86045. if (_this.shouldRender) {
  86046. _this.render();
  86047. }
  86048. });
  86049. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  86050. _this.dispose();
  86051. });
  86052. }
  86053. /**
  86054. * Renders the utility layers scene on top of the original scene
  86055. */
  86056. UtilityLayerRenderer.prototype.render = function () {
  86057. this._updateCamera();
  86058. this.utilityLayerScene.render();
  86059. };
  86060. /**
  86061. * Disposes of the renderer
  86062. */
  86063. UtilityLayerRenderer.prototype.dispose = function () {
  86064. if (this._afterRenderObserver) {
  86065. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  86066. }
  86067. if (this._sceneDisposeObserver) {
  86068. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  86069. }
  86070. this.utilityLayerScene.dispose();
  86071. };
  86072. UtilityLayerRenderer.prototype._updateCamera = function () {
  86073. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  86074. };
  86075. return UtilityLayerRenderer;
  86076. }());
  86077. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  86078. })(BABYLON || (BABYLON = {}));
  86079. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  86080. var BABYLON;
  86081. (function (BABYLON) {
  86082. /**
  86083. * Defines a target to use with MorphTargetManager
  86084. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  86085. */
  86086. var MorphTarget = /** @class */ (function () {
  86087. /**
  86088. * Creates a new MorphTarget
  86089. * @param name defines the name of the target
  86090. * @param influence defines the influence to use
  86091. */
  86092. function MorphTarget(
  86093. /** defines the name of the target */
  86094. name, influence, scene) {
  86095. if (influence === void 0) { influence = 0; }
  86096. if (scene === void 0) { scene = null; }
  86097. this.name = name;
  86098. /**
  86099. * Gets or sets the list of animations
  86100. */
  86101. this.animations = new Array();
  86102. this._positions = null;
  86103. this._normals = null;
  86104. this._tangents = null;
  86105. /**
  86106. * Observable raised when the influence changes
  86107. */
  86108. this.onInfluenceChanged = new BABYLON.Observable();
  86109. this._animationPropertiesOverride = null;
  86110. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86111. this.influence = influence;
  86112. }
  86113. Object.defineProperty(MorphTarget.prototype, "influence", {
  86114. /**
  86115. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  86116. */
  86117. get: function () {
  86118. return this._influence;
  86119. },
  86120. set: function (influence) {
  86121. if (this._influence === influence) {
  86122. return;
  86123. }
  86124. var previous = this._influence;
  86125. this._influence = influence;
  86126. if (this.onInfluenceChanged.hasObservers) {
  86127. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  86128. }
  86129. },
  86130. enumerable: true,
  86131. configurable: true
  86132. });
  86133. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  86134. /**
  86135. * Gets or sets the animation properties override
  86136. */
  86137. get: function () {
  86138. if (!this._animationPropertiesOverride && this._scene) {
  86139. return this._scene.animationPropertiesOverride;
  86140. }
  86141. return this._animationPropertiesOverride;
  86142. },
  86143. set: function (value) {
  86144. this._animationPropertiesOverride = value;
  86145. },
  86146. enumerable: true,
  86147. configurable: true
  86148. });
  86149. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  86150. /**
  86151. * Gets a boolean defining if the target contains position data
  86152. */
  86153. get: function () {
  86154. return !!this._positions;
  86155. },
  86156. enumerable: true,
  86157. configurable: true
  86158. });
  86159. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  86160. /**
  86161. * Gets a boolean defining if the target contains normal data
  86162. */
  86163. get: function () {
  86164. return !!this._normals;
  86165. },
  86166. enumerable: true,
  86167. configurable: true
  86168. });
  86169. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  86170. /**
  86171. * Gets a boolean defining if the target contains tangent data
  86172. */
  86173. get: function () {
  86174. return !!this._tangents;
  86175. },
  86176. enumerable: true,
  86177. configurable: true
  86178. });
  86179. /**
  86180. * Affects position data to this target
  86181. * @param data defines the position data to use
  86182. */
  86183. MorphTarget.prototype.setPositions = function (data) {
  86184. this._positions = data;
  86185. };
  86186. /**
  86187. * Gets the position data stored in this target
  86188. * @returns a FloatArray containing the position data (or null if not present)
  86189. */
  86190. MorphTarget.prototype.getPositions = function () {
  86191. return this._positions;
  86192. };
  86193. /**
  86194. * Affects normal data to this target
  86195. * @param data defines the normal data to use
  86196. */
  86197. MorphTarget.prototype.setNormals = function (data) {
  86198. this._normals = data;
  86199. };
  86200. /**
  86201. * Gets the normal data stored in this target
  86202. * @returns a FloatArray containing the normal data (or null if not present)
  86203. */
  86204. MorphTarget.prototype.getNormals = function () {
  86205. return this._normals;
  86206. };
  86207. /**
  86208. * Affects tangent data to this target
  86209. * @param data defines the tangent data to use
  86210. */
  86211. MorphTarget.prototype.setTangents = function (data) {
  86212. this._tangents = data;
  86213. };
  86214. /**
  86215. * Gets the tangent data stored in this target
  86216. * @returns a FloatArray containing the tangent data (or null if not present)
  86217. */
  86218. MorphTarget.prototype.getTangents = function () {
  86219. return this._tangents;
  86220. };
  86221. /**
  86222. * Serializes the current target into a Serialization object
  86223. * @returns the serialized object
  86224. */
  86225. MorphTarget.prototype.serialize = function () {
  86226. var serializationObject = {};
  86227. serializationObject.name = this.name;
  86228. serializationObject.influence = this.influence;
  86229. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  86230. if (this.hasNormals) {
  86231. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  86232. }
  86233. if (this.hasTangents) {
  86234. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  86235. }
  86236. // Animations
  86237. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  86238. return serializationObject;
  86239. };
  86240. // Statics
  86241. /**
  86242. * Creates a new target from serialized data
  86243. * @param serializationObject defines the serialized data to use
  86244. * @returns a new MorphTarget
  86245. */
  86246. MorphTarget.Parse = function (serializationObject) {
  86247. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  86248. result.setPositions(serializationObject.positions);
  86249. if (serializationObject.normals) {
  86250. result.setNormals(serializationObject.normals);
  86251. }
  86252. if (serializationObject.tangents) {
  86253. result.setTangents(serializationObject.tangents);
  86254. }
  86255. // Animations
  86256. if (serializationObject.animations) {
  86257. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  86258. var parsedAnimation = serializationObject.animations[animationIndex];
  86259. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  86260. }
  86261. }
  86262. return result;
  86263. };
  86264. /**
  86265. * Creates a MorphTarget from mesh data
  86266. * @param mesh defines the source mesh
  86267. * @param name defines the name to use for the new target
  86268. * @param influence defines the influence to attach to the target
  86269. * @returns a new MorphTarget
  86270. */
  86271. MorphTarget.FromMesh = function (mesh, name, influence) {
  86272. if (!name) {
  86273. name = mesh.name;
  86274. }
  86275. var result = new MorphTarget(name, influence, mesh.getScene());
  86276. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86277. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  86278. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  86279. }
  86280. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  86281. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  86282. }
  86283. return result;
  86284. };
  86285. return MorphTarget;
  86286. }());
  86287. BABYLON.MorphTarget = MorphTarget;
  86288. })(BABYLON || (BABYLON = {}));
  86289. //# sourceMappingURL=babylon.morphTarget.js.map
  86290. var BABYLON;
  86291. (function (BABYLON) {
  86292. /**
  86293. * This class is used to deform meshes using morphing between different targets
  86294. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  86295. */
  86296. var MorphTargetManager = /** @class */ (function () {
  86297. /**
  86298. * Creates a new MorphTargetManager
  86299. * @param scene defines the current scene
  86300. */
  86301. function MorphTargetManager(scene) {
  86302. if (scene === void 0) { scene = null; }
  86303. this._targets = new Array();
  86304. this._targetObservable = new Array();
  86305. this._activeTargets = new BABYLON.SmartArray(16);
  86306. this._supportsNormals = false;
  86307. this._supportsTangents = false;
  86308. this._vertexCount = 0;
  86309. this._uniqueId = 0;
  86310. this._tempInfluences = new Array();
  86311. if (!scene) {
  86312. scene = BABYLON.Engine.LastCreatedScene;
  86313. }
  86314. this._scene = scene;
  86315. if (this._scene) {
  86316. this._scene.morphTargetManagers.push(this);
  86317. this._uniqueId = this._scene.getUniqueId();
  86318. }
  86319. }
  86320. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  86321. /**
  86322. * Gets the unique ID of this manager
  86323. */
  86324. get: function () {
  86325. return this._uniqueId;
  86326. },
  86327. enumerable: true,
  86328. configurable: true
  86329. });
  86330. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  86331. /**
  86332. * Gets the number of vertices handled by this manager
  86333. */
  86334. get: function () {
  86335. return this._vertexCount;
  86336. },
  86337. enumerable: true,
  86338. configurable: true
  86339. });
  86340. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  86341. /**
  86342. * Gets a boolean indicating if this manager supports morphing of normals
  86343. */
  86344. get: function () {
  86345. return this._supportsNormals;
  86346. },
  86347. enumerable: true,
  86348. configurable: true
  86349. });
  86350. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  86351. /**
  86352. * Gets a boolean indicating if this manager supports morphing of tangents
  86353. */
  86354. get: function () {
  86355. return this._supportsTangents;
  86356. },
  86357. enumerable: true,
  86358. configurable: true
  86359. });
  86360. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  86361. /**
  86362. * Gets the number of targets stored in this manager
  86363. */
  86364. get: function () {
  86365. return this._targets.length;
  86366. },
  86367. enumerable: true,
  86368. configurable: true
  86369. });
  86370. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  86371. /**
  86372. * Gets the number of influencers (ie. the number of targets with influences > 0)
  86373. */
  86374. get: function () {
  86375. return this._activeTargets.length;
  86376. },
  86377. enumerable: true,
  86378. configurable: true
  86379. });
  86380. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  86381. /**
  86382. * Gets the list of influences (one per target)
  86383. */
  86384. get: function () {
  86385. return this._influences;
  86386. },
  86387. enumerable: true,
  86388. configurable: true
  86389. });
  86390. /**
  86391. * Gets the active target at specified index. An active target is a target with an influence > 0
  86392. * @param index defines the index to check
  86393. * @returns the requested target
  86394. */
  86395. MorphTargetManager.prototype.getActiveTarget = function (index) {
  86396. return this._activeTargets.data[index];
  86397. };
  86398. /**
  86399. * Gets the target at specified index
  86400. * @param index defines the index to check
  86401. * @returns the requested target
  86402. */
  86403. MorphTargetManager.prototype.getTarget = function (index) {
  86404. return this._targets[index];
  86405. };
  86406. /**
  86407. * Add a new target to this manager
  86408. * @param target defines the target to add
  86409. */
  86410. MorphTargetManager.prototype.addTarget = function (target) {
  86411. var _this = this;
  86412. this._targets.push(target);
  86413. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  86414. _this._syncActiveTargets(needUpdate);
  86415. }));
  86416. this._syncActiveTargets(true);
  86417. };
  86418. /**
  86419. * Removes a target from the manager
  86420. * @param target defines the target to remove
  86421. */
  86422. MorphTargetManager.prototype.removeTarget = function (target) {
  86423. var index = this._targets.indexOf(target);
  86424. if (index >= 0) {
  86425. this._targets.splice(index, 1);
  86426. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  86427. this._syncActiveTargets(true);
  86428. }
  86429. };
  86430. /**
  86431. * Serializes the current manager into a Serialization object
  86432. * @returns the serialized object
  86433. */
  86434. MorphTargetManager.prototype.serialize = function () {
  86435. var serializationObject = {};
  86436. serializationObject.id = this.uniqueId;
  86437. serializationObject.targets = [];
  86438. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86439. var target = _a[_i];
  86440. serializationObject.targets.push(target.serialize());
  86441. }
  86442. return serializationObject;
  86443. };
  86444. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  86445. var influenceCount = 0;
  86446. this._activeTargets.reset();
  86447. this._supportsNormals = true;
  86448. this._supportsTangents = true;
  86449. this._vertexCount = 0;
  86450. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86451. var target = _a[_i];
  86452. this._activeTargets.push(target);
  86453. this._tempInfluences[influenceCount++] = target.influence;
  86454. var positions = target.getPositions();
  86455. if (positions) {
  86456. this._supportsNormals = this._supportsNormals && target.hasNormals;
  86457. this._supportsTangents = this._supportsTangents && target.hasTangents;
  86458. var vertexCount = positions.length / 3;
  86459. if (this._vertexCount === 0) {
  86460. this._vertexCount = vertexCount;
  86461. }
  86462. else if (this._vertexCount !== vertexCount) {
  86463. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  86464. return;
  86465. }
  86466. }
  86467. }
  86468. if (!this._influences || this._influences.length !== influenceCount) {
  86469. this._influences = new Float32Array(influenceCount);
  86470. }
  86471. for (var index = 0; index < influenceCount; index++) {
  86472. this._influences[index] = this._tempInfluences[index];
  86473. }
  86474. if (needUpdate) {
  86475. this.synchronize();
  86476. }
  86477. };
  86478. /**
  86479. * Syncrhonize the targets with all the meshes using this morph target manager
  86480. */
  86481. MorphTargetManager.prototype.synchronize = function () {
  86482. if (!this._scene) {
  86483. return;
  86484. }
  86485. // Flag meshes as dirty to resync with the active targets
  86486. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  86487. var mesh = _a[_i];
  86488. if (mesh.morphTargetManager === this) {
  86489. mesh._syncGeometryWithMorphTargetManager();
  86490. }
  86491. }
  86492. };
  86493. // Statics
  86494. /**
  86495. * Creates a new MorphTargetManager from serialized data
  86496. * @param serializationObject defines the serialized data
  86497. * @param scene defines the hosting scene
  86498. * @returns the new MorphTargetManager
  86499. */
  86500. MorphTargetManager.Parse = function (serializationObject, scene) {
  86501. var result = new MorphTargetManager(scene);
  86502. result._uniqueId = serializationObject.id;
  86503. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  86504. var targetData = _a[_i];
  86505. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  86506. }
  86507. return result;
  86508. };
  86509. return MorphTargetManager;
  86510. }());
  86511. BABYLON.MorphTargetManager = MorphTargetManager;
  86512. })(BABYLON || (BABYLON = {}));
  86513. //# sourceMappingURL=babylon.morphTargetManager.js.map
  86514. var BABYLON;
  86515. (function (BABYLON) {
  86516. var Octree = /** @class */ (function () {
  86517. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  86518. if (maxDepth === void 0) { maxDepth = 2; }
  86519. this.maxDepth = maxDepth;
  86520. this.dynamicContent = new Array();
  86521. this._maxBlockCapacity = maxBlockCapacity || 64;
  86522. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  86523. this._creationFunc = creationFunc;
  86524. }
  86525. // Methods
  86526. Octree.prototype.update = function (worldMin, worldMax, entries) {
  86527. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  86528. };
  86529. Octree.prototype.addMesh = function (entry) {
  86530. for (var index = 0; index < this.blocks.length; index++) {
  86531. var block = this.blocks[index];
  86532. block.addEntry(entry);
  86533. }
  86534. };
  86535. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  86536. this._selectionContent.reset();
  86537. for (var index = 0; index < this.blocks.length; index++) {
  86538. var block = this.blocks[index];
  86539. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  86540. }
  86541. if (allowDuplicate) {
  86542. this._selectionContent.concat(this.dynamicContent);
  86543. }
  86544. else {
  86545. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86546. }
  86547. return this._selectionContent;
  86548. };
  86549. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86550. this._selectionContent.reset();
  86551. for (var index = 0; index < this.blocks.length; index++) {
  86552. var block = this.blocks[index];
  86553. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86554. }
  86555. if (allowDuplicate) {
  86556. this._selectionContent.concat(this.dynamicContent);
  86557. }
  86558. else {
  86559. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86560. }
  86561. return this._selectionContent;
  86562. };
  86563. Octree.prototype.intersectsRay = function (ray) {
  86564. this._selectionContent.reset();
  86565. for (var index = 0; index < this.blocks.length; index++) {
  86566. var block = this.blocks[index];
  86567. block.intersectsRay(ray, this._selectionContent);
  86568. }
  86569. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86570. return this._selectionContent;
  86571. };
  86572. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86573. target.blocks = new Array();
  86574. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86575. // Segmenting space
  86576. for (var x = 0; x < 2; x++) {
  86577. for (var y = 0; y < 2; y++) {
  86578. for (var z = 0; z < 2; z++) {
  86579. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86580. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86581. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86582. block.addEntries(entries);
  86583. target.blocks.push(block);
  86584. }
  86585. }
  86586. }
  86587. };
  86588. Octree.CreationFuncForMeshes = function (entry, block) {
  86589. var boundingInfo = entry.getBoundingInfo();
  86590. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86591. block.entries.push(entry);
  86592. }
  86593. };
  86594. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86595. var boundingInfo = entry.getBoundingInfo();
  86596. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86597. block.entries.push(entry);
  86598. }
  86599. };
  86600. return Octree;
  86601. }());
  86602. BABYLON.Octree = Octree;
  86603. })(BABYLON || (BABYLON = {}));
  86604. //# sourceMappingURL=babylon.octree.js.map
  86605. var BABYLON;
  86606. (function (BABYLON) {
  86607. var OctreeBlock = /** @class */ (function () {
  86608. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86609. this.entries = new Array();
  86610. this._boundingVectors = new Array();
  86611. this._capacity = capacity;
  86612. this._depth = depth;
  86613. this._maxDepth = maxDepth;
  86614. this._creationFunc = creationFunc;
  86615. this._minPoint = minPoint;
  86616. this._maxPoint = maxPoint;
  86617. this._boundingVectors.push(minPoint.clone());
  86618. this._boundingVectors.push(maxPoint.clone());
  86619. this._boundingVectors.push(minPoint.clone());
  86620. this._boundingVectors[2].x = maxPoint.x;
  86621. this._boundingVectors.push(minPoint.clone());
  86622. this._boundingVectors[3].y = maxPoint.y;
  86623. this._boundingVectors.push(minPoint.clone());
  86624. this._boundingVectors[4].z = maxPoint.z;
  86625. this._boundingVectors.push(maxPoint.clone());
  86626. this._boundingVectors[5].z = minPoint.z;
  86627. this._boundingVectors.push(maxPoint.clone());
  86628. this._boundingVectors[6].x = minPoint.x;
  86629. this._boundingVectors.push(maxPoint.clone());
  86630. this._boundingVectors[7].y = minPoint.y;
  86631. }
  86632. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86633. // Property
  86634. get: function () {
  86635. return this._capacity;
  86636. },
  86637. enumerable: true,
  86638. configurable: true
  86639. });
  86640. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86641. get: function () {
  86642. return this._minPoint;
  86643. },
  86644. enumerable: true,
  86645. configurable: true
  86646. });
  86647. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86648. get: function () {
  86649. return this._maxPoint;
  86650. },
  86651. enumerable: true,
  86652. configurable: true
  86653. });
  86654. // Methods
  86655. OctreeBlock.prototype.addEntry = function (entry) {
  86656. if (this.blocks) {
  86657. for (var index = 0; index < this.blocks.length; index++) {
  86658. var block = this.blocks[index];
  86659. block.addEntry(entry);
  86660. }
  86661. return;
  86662. }
  86663. this._creationFunc(entry, this);
  86664. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86665. this.createInnerBlocks();
  86666. }
  86667. };
  86668. OctreeBlock.prototype.addEntries = function (entries) {
  86669. for (var index = 0; index < entries.length; index++) {
  86670. var mesh = entries[index];
  86671. this.addEntry(mesh);
  86672. }
  86673. };
  86674. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86675. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86676. if (this.blocks) {
  86677. for (var index = 0; index < this.blocks.length; index++) {
  86678. var block = this.blocks[index];
  86679. block.select(frustumPlanes, selection, allowDuplicate);
  86680. }
  86681. return;
  86682. }
  86683. if (allowDuplicate) {
  86684. selection.concat(this.entries);
  86685. }
  86686. else {
  86687. selection.concatWithNoDuplicate(this.entries);
  86688. }
  86689. }
  86690. };
  86691. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86692. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86693. if (this.blocks) {
  86694. for (var index = 0; index < this.blocks.length; index++) {
  86695. var block = this.blocks[index];
  86696. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86697. }
  86698. return;
  86699. }
  86700. if (allowDuplicate) {
  86701. selection.concat(this.entries);
  86702. }
  86703. else {
  86704. selection.concatWithNoDuplicate(this.entries);
  86705. }
  86706. }
  86707. };
  86708. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86709. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86710. if (this.blocks) {
  86711. for (var index = 0; index < this.blocks.length; index++) {
  86712. var block = this.blocks[index];
  86713. block.intersectsRay(ray, selection);
  86714. }
  86715. return;
  86716. }
  86717. selection.concatWithNoDuplicate(this.entries);
  86718. }
  86719. };
  86720. OctreeBlock.prototype.createInnerBlocks = function () {
  86721. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86722. };
  86723. return OctreeBlock;
  86724. }());
  86725. BABYLON.OctreeBlock = OctreeBlock;
  86726. })(BABYLON || (BABYLON = {}));
  86727. //# sourceMappingURL=babylon.octreeBlock.js.map
  86728. var BABYLON;
  86729. (function (BABYLON) {
  86730. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86731. __extends(VRDistortionCorrectionPostProcess, _super);
  86732. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86733. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86734. 'LensCenter',
  86735. 'Scale',
  86736. 'ScaleIn',
  86737. 'HmdWarpParam'
  86738. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86739. _this._isRightEye = isRightEye;
  86740. _this._distortionFactors = vrMetrics.distortionK;
  86741. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86742. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86743. _this.adaptScaleToCurrentViewport = true;
  86744. _this.onSizeChangedObservable.add(function () {
  86745. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86746. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86747. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86748. });
  86749. _this.onApplyObservable.add(function (effect) {
  86750. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86751. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86752. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86753. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86754. });
  86755. return _this;
  86756. }
  86757. return VRDistortionCorrectionPostProcess;
  86758. }(BABYLON.PostProcess));
  86759. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86760. })(BABYLON || (BABYLON = {}));
  86761. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86762. var BABYLON;
  86763. (function (BABYLON) {
  86764. /**
  86765. * Postprocess used to generate anaglyphic rendering
  86766. */
  86767. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86768. __extends(AnaglyphPostProcess, _super);
  86769. /**
  86770. * Creates a new AnaglyphPostProcess
  86771. * @param name defines postprocess name
  86772. * @param options defines creation options or target ratio scale
  86773. * @param rigCameras defines cameras using this postprocess
  86774. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86775. * @param engine defines hosting engine
  86776. * @param reusable defines if the postprocess will be reused multiple times per frame
  86777. */
  86778. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86779. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86780. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86781. _this.onApplyObservable.add(function (effect) {
  86782. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86783. });
  86784. return _this;
  86785. }
  86786. return AnaglyphPostProcess;
  86787. }(BABYLON.PostProcess));
  86788. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86789. })(BABYLON || (BABYLON = {}));
  86790. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86791. var BABYLON;
  86792. (function (BABYLON) {
  86793. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86794. __extends(StereoscopicInterlacePostProcess, _super);
  86795. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86796. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86797. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86798. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86799. _this.onSizeChangedObservable.add(function () {
  86800. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86801. });
  86802. _this.onApplyObservable.add(function (effect) {
  86803. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86804. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86805. });
  86806. return _this;
  86807. }
  86808. return StereoscopicInterlacePostProcess;
  86809. }(BABYLON.PostProcess));
  86810. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86811. })(BABYLON || (BABYLON = {}));
  86812. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86813. var BABYLON;
  86814. (function (BABYLON) {
  86815. /**
  86816. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86817. * Screen rotation is taken into account.
  86818. */
  86819. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86820. function FreeCameraDeviceOrientationInput() {
  86821. var _this = this;
  86822. this._screenOrientationAngle = 0;
  86823. this._screenQuaternion = new BABYLON.Quaternion();
  86824. this._alpha = 0;
  86825. this._beta = 0;
  86826. this._gamma = 0;
  86827. this._orientationChanged = function () {
  86828. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86829. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86830. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86831. };
  86832. this._deviceOrientation = function (evt) {
  86833. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86834. _this._beta = evt.beta !== null ? evt.beta : 0;
  86835. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86836. };
  86837. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86838. this._orientationChanged();
  86839. }
  86840. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86841. get: function () {
  86842. return this._camera;
  86843. },
  86844. set: function (camera) {
  86845. this._camera = camera;
  86846. if (this._camera != null && !this._camera.rotationQuaternion) {
  86847. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86848. }
  86849. },
  86850. enumerable: true,
  86851. configurable: true
  86852. });
  86853. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86854. window.addEventListener("orientationchange", this._orientationChanged);
  86855. window.addEventListener("deviceorientation", this._deviceOrientation);
  86856. //In certain cases, the attach control is called AFTER orientation was changed,
  86857. //So this is needed.
  86858. this._orientationChanged();
  86859. };
  86860. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86861. window.removeEventListener("orientationchange", this._orientationChanged);
  86862. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86863. };
  86864. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86865. //if no device orientation provided, don't update the rotation.
  86866. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86867. if (!this._alpha)
  86868. return;
  86869. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86870. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86871. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86872. //Mirror on XY Plane
  86873. this._camera.rotationQuaternion.z *= -1;
  86874. this._camera.rotationQuaternion.w *= -1;
  86875. };
  86876. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86877. return "FreeCameraDeviceOrientationInput";
  86878. };
  86879. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86880. return "deviceOrientation";
  86881. };
  86882. return FreeCameraDeviceOrientationInput;
  86883. }());
  86884. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86885. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86886. })(BABYLON || (BABYLON = {}));
  86887. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86888. var BABYLON;
  86889. (function (BABYLON) {
  86890. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86891. function ArcRotateCameraVRDeviceOrientationInput() {
  86892. this.alphaCorrection = 1;
  86893. this.betaCorrection = 1;
  86894. this.gammaCorrection = 1;
  86895. this._alpha = 0;
  86896. this._gamma = 0;
  86897. this._dirty = false;
  86898. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86899. }
  86900. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86901. this.camera.attachControl(element, noPreventDefault);
  86902. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86903. };
  86904. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86905. if (evt.alpha !== null) {
  86906. this._alpha = +evt.alpha | 0;
  86907. }
  86908. if (evt.gamma !== null) {
  86909. this._gamma = +evt.gamma | 0;
  86910. }
  86911. this._dirty = true;
  86912. };
  86913. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86914. if (this._dirty) {
  86915. this._dirty = false;
  86916. if (this._gamma < 0) {
  86917. this._gamma = 180 + this._gamma;
  86918. }
  86919. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86920. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86921. }
  86922. };
  86923. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86924. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86925. };
  86926. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86927. return "ArcRotateCameraVRDeviceOrientationInput";
  86928. };
  86929. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86930. return "VRDeviceOrientation";
  86931. };
  86932. return ArcRotateCameraVRDeviceOrientationInput;
  86933. }());
  86934. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86935. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86936. })(BABYLON || (BABYLON = {}));
  86937. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86938. var BABYLON;
  86939. (function (BABYLON) {
  86940. var VRCameraMetrics = /** @class */ (function () {
  86941. function VRCameraMetrics() {
  86942. this.compensateDistortion = true;
  86943. }
  86944. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86945. get: function () {
  86946. return this.hResolution / (2 * this.vResolution);
  86947. },
  86948. enumerable: true,
  86949. configurable: true
  86950. });
  86951. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86952. get: function () {
  86953. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86954. },
  86955. enumerable: true,
  86956. configurable: true
  86957. });
  86958. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86959. get: function () {
  86960. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86961. var h = (4 * meters) / this.hScreenSize;
  86962. return BABYLON.Matrix.Translation(h, 0, 0);
  86963. },
  86964. enumerable: true,
  86965. configurable: true
  86966. });
  86967. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86968. get: function () {
  86969. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86970. var h = (4 * meters) / this.hScreenSize;
  86971. return BABYLON.Matrix.Translation(-h, 0, 0);
  86972. },
  86973. enumerable: true,
  86974. configurable: true
  86975. });
  86976. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86977. get: function () {
  86978. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86979. },
  86980. enumerable: true,
  86981. configurable: true
  86982. });
  86983. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86984. get: function () {
  86985. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86986. },
  86987. enumerable: true,
  86988. configurable: true
  86989. });
  86990. VRCameraMetrics.GetDefault = function () {
  86991. var result = new VRCameraMetrics();
  86992. result.hResolution = 1280;
  86993. result.vResolution = 800;
  86994. result.hScreenSize = 0.149759993;
  86995. result.vScreenSize = 0.0935999975;
  86996. result.vScreenCenter = 0.0467999987;
  86997. result.eyeToScreenDistance = 0.0410000011;
  86998. result.lensSeparationDistance = 0.0635000020;
  86999. result.interpupillaryDistance = 0.0640000030;
  87000. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  87001. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  87002. result.postProcessScaleFactor = 1.714605507808412;
  87003. result.lensCenterOffset = 0.151976421;
  87004. return result;
  87005. };
  87006. return VRCameraMetrics;
  87007. }());
  87008. BABYLON.VRCameraMetrics = VRCameraMetrics;
  87009. })(BABYLON || (BABYLON = {}));
  87010. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  87011. var BABYLON;
  87012. (function (BABYLON) {
  87013. /**
  87014. * This represents a WebVR camera.
  87015. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  87016. * @example http://doc.babylonjs.com/how_to/webvr_camera
  87017. */
  87018. var WebVRFreeCamera = /** @class */ (function (_super) {
  87019. __extends(WebVRFreeCamera, _super);
  87020. /**
  87021. * Instantiates a WebVRFreeCamera.
  87022. * @param name The name of the WebVRFreeCamera
  87023. * @param position The starting anchor position for the camera
  87024. * @param scene The scene the camera belongs to
  87025. * @param webVROptions a set of customizable options for the webVRCamera
  87026. */
  87027. function WebVRFreeCamera(name, position, scene, webVROptions) {
  87028. if (webVROptions === void 0) { webVROptions = {}; }
  87029. var _this = _super.call(this, name, position, scene) || this;
  87030. _this.webVROptions = webVROptions;
  87031. /**
  87032. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  87033. */
  87034. _this._vrDevice = null;
  87035. /**
  87036. * The rawPose of the vrDevice.
  87037. */
  87038. _this.rawPose = null;
  87039. _this._specsVersion = "1.1";
  87040. _this._attached = false;
  87041. _this._descendants = [];
  87042. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  87043. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  87044. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  87045. _this._standingMatrix = null;
  87046. /**
  87047. * Represents device position in babylon space.
  87048. */
  87049. _this.devicePosition = BABYLON.Vector3.Zero();
  87050. /**
  87051. * Represents device rotation in babylon space.
  87052. */
  87053. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  87054. /**
  87055. * The scale of the device to be used when translating from device space to babylon space.
  87056. */
  87057. _this.deviceScaleFactor = 1;
  87058. _this._deviceToWorld = BABYLON.Matrix.Identity();
  87059. _this._worldToDevice = BABYLON.Matrix.Identity();
  87060. /**
  87061. * References to the webVR controllers for the vrDevice.
  87062. */
  87063. _this.controllers = [];
  87064. /**
  87065. * Emits an event when a controller is attached.
  87066. */
  87067. _this.onControllersAttachedObservable = new BABYLON.Observable();
  87068. /**
  87069. * Emits an event when a controller's mesh has been loaded;
  87070. */
  87071. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87072. /**
  87073. * If the rig cameras be used as parent instead of this camera.
  87074. */
  87075. _this.rigParenting = true;
  87076. _this._defaultHeight = undefined;
  87077. _this._workingVector = BABYLON.Vector3.Zero();
  87078. _this._oneVector = BABYLON.Vector3.One();
  87079. _this._workingMatrix = BABYLON.Matrix.Identity();
  87080. _this._cache.position = BABYLON.Vector3.Zero();
  87081. if (webVROptions.defaultHeight) {
  87082. _this._defaultHeight = webVROptions.defaultHeight;
  87083. _this.position.y = _this._defaultHeight;
  87084. }
  87085. _this.minZ = 0.1;
  87086. //legacy support - the compensation boolean was removed.
  87087. if (arguments.length === 5) {
  87088. _this.webVROptions = arguments[4];
  87089. }
  87090. // default webVR options
  87091. if (_this.webVROptions.trackPosition == undefined) {
  87092. _this.webVROptions.trackPosition = true;
  87093. }
  87094. if (_this.webVROptions.controllerMeshes == undefined) {
  87095. _this.webVROptions.controllerMeshes = true;
  87096. }
  87097. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  87098. _this.webVROptions.defaultLightingOnControllers = true;
  87099. }
  87100. _this.rotationQuaternion = new BABYLON.Quaternion();
  87101. if (_this.webVROptions && _this.webVROptions.positionScale) {
  87102. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  87103. }
  87104. //enable VR
  87105. var engine = _this.getEngine();
  87106. _this._onVREnabled = function (success) { if (success) {
  87107. _this.initControllers();
  87108. } };
  87109. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  87110. engine.initWebVR().add(function (event) {
  87111. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  87112. return;
  87113. }
  87114. _this._vrDevice = event.vrDisplay;
  87115. //reset the rig parameters.
  87116. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  87117. if (_this._attached) {
  87118. _this.getEngine().enableVR();
  87119. }
  87120. });
  87121. if (typeof (VRFrameData) !== "undefined")
  87122. _this._frameData = new VRFrameData();
  87123. /**
  87124. * The idea behind the following lines:
  87125. * objects that have the camera as parent should actually have the rig cameras as a parent.
  87126. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  87127. * the second will not show it correctly.
  87128. *
  87129. * To solve this - each object that has the camera as parent will be added to a protected array.
  87130. * When the rig camera renders, it will take this array and set all of those to be its children.
  87131. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  87132. * Amazing!
  87133. */
  87134. scene.onBeforeCameraRenderObservable.add(function (camera) {
  87135. if (camera.parent === _this && _this.rigParenting) {
  87136. _this._descendants = _this.getDescendants(true, function (n) {
  87137. // don't take the cameras or the controllers!
  87138. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  87139. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  87140. return !isController && !isRigCamera;
  87141. });
  87142. _this._descendants.forEach(function (node) {
  87143. node.parent = camera;
  87144. });
  87145. }
  87146. });
  87147. scene.onAfterCameraRenderObservable.add(function (camera) {
  87148. if (camera.parent === _this && _this.rigParenting) {
  87149. _this._descendants.forEach(function (node) {
  87150. node.parent = _this;
  87151. });
  87152. }
  87153. });
  87154. return _this;
  87155. }
  87156. /**
  87157. * Gets the device distance from the ground in meters.
  87158. * @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.
  87159. */
  87160. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  87161. if (this._standingMatrix) {
  87162. // Add standing matrix offset to get real offset from ground in room
  87163. this._standingMatrix.getTranslationToRef(this._workingVector);
  87164. return this._deviceRoomPosition.y + this._workingVector.y;
  87165. }
  87166. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  87167. return this._defaultHeight || 0;
  87168. };
  87169. /**
  87170. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  87171. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  87172. */
  87173. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  87174. var _this = this;
  87175. if (callback === void 0) { callback = function (bool) { }; }
  87176. // Use standing matrix if available
  87177. this.getEngine().initWebVRAsync().then(function (result) {
  87178. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  87179. callback(false);
  87180. }
  87181. else {
  87182. _this._standingMatrix = new BABYLON.Matrix();
  87183. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  87184. if (!_this.getScene().useRightHandedSystem) {
  87185. [2, 6, 8, 9, 14].forEach(function (num) {
  87186. if (_this._standingMatrix) {
  87187. _this._standingMatrix.m[num] *= -1;
  87188. }
  87189. });
  87190. }
  87191. callback(true);
  87192. }
  87193. });
  87194. };
  87195. /**
  87196. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  87197. * @returns A promise with a boolean set to if the standing matrix is supported.
  87198. */
  87199. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  87200. var _this = this;
  87201. return new Promise(function (res, rej) {
  87202. _this.useStandingMatrix(function (supported) {
  87203. res(supported);
  87204. });
  87205. });
  87206. };
  87207. /**
  87208. * Disposes the camera
  87209. */
  87210. WebVRFreeCamera.prototype.dispose = function () {
  87211. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  87212. _super.prototype.dispose.call(this);
  87213. };
  87214. /**
  87215. * Gets a vrController by name.
  87216. * @param name The name of the controller to retreive
  87217. * @returns the controller matching the name specified or null if not found
  87218. */
  87219. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  87220. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  87221. var gp = _a[_i];
  87222. if (gp.hand === name) {
  87223. return gp;
  87224. }
  87225. }
  87226. return null;
  87227. };
  87228. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  87229. /**
  87230. * The controller corrisponding to the users left hand.
  87231. */
  87232. get: function () {
  87233. if (!this._leftController) {
  87234. this._leftController = this.getControllerByName("left");
  87235. }
  87236. return this._leftController;
  87237. },
  87238. enumerable: true,
  87239. configurable: true
  87240. });
  87241. ;
  87242. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  87243. /**
  87244. * The controller corrisponding to the users right hand.
  87245. */
  87246. get: function () {
  87247. if (!this._rightController) {
  87248. this._rightController = this.getControllerByName("right");
  87249. }
  87250. return this._rightController;
  87251. },
  87252. enumerable: true,
  87253. configurable: true
  87254. });
  87255. ;
  87256. /**
  87257. * Casts a ray forward from the vrCamera's gaze.
  87258. * @param length Length of the ray (default: 100)
  87259. * @returns the ray corrisponding to the gaze
  87260. */
  87261. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  87262. if (length === void 0) { length = 100; }
  87263. if (this.leftCamera) {
  87264. // Use left eye to avoid computation to compute center on every call
  87265. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  87266. }
  87267. else {
  87268. return _super.prototype.getForwardRay.call(this, length);
  87269. }
  87270. };
  87271. /**
  87272. * Updates the camera based on device's frame data
  87273. */
  87274. WebVRFreeCamera.prototype._checkInputs = function () {
  87275. if (this._vrDevice && this._vrDevice.isPresenting) {
  87276. this._vrDevice.getFrameData(this._frameData);
  87277. this.updateFromDevice(this._frameData.pose);
  87278. }
  87279. _super.prototype._checkInputs.call(this);
  87280. };
  87281. /**
  87282. * Updates the poseControlled values based on the input device pose.
  87283. * @param poseData Pose coming from the device
  87284. */
  87285. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  87286. if (poseData && poseData.orientation) {
  87287. this.rawPose = poseData;
  87288. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  87289. if (this.getScene().useRightHandedSystem) {
  87290. this._deviceRoomRotationQuaternion.z *= -1;
  87291. this._deviceRoomRotationQuaternion.w *= -1;
  87292. }
  87293. if (this.webVROptions.trackPosition && this.rawPose.position) {
  87294. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  87295. if (this.getScene().useRightHandedSystem) {
  87296. this._deviceRoomPosition.z *= -1;
  87297. }
  87298. }
  87299. }
  87300. };
  87301. /**
  87302. * WebVR's attach control will start broadcasting frames to the device.
  87303. * Note that in certain browsers (chrome for example) this function must be called
  87304. * within a user-interaction callback. Example:
  87305. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  87306. *
  87307. * @param element html element to attach the vrDevice to
  87308. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  87309. */
  87310. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  87311. _super.prototype.attachControl.call(this, element, noPreventDefault);
  87312. this._attached = true;
  87313. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  87314. if (this._vrDevice) {
  87315. this.getEngine().enableVR();
  87316. }
  87317. };
  87318. /**
  87319. * Detaches the camera from the html element and disables VR
  87320. *
  87321. * @param element html element to detach from
  87322. */
  87323. WebVRFreeCamera.prototype.detachControl = function (element) {
  87324. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  87325. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  87326. _super.prototype.detachControl.call(this, element);
  87327. this._attached = false;
  87328. this.getEngine().disableVR();
  87329. };
  87330. /**
  87331. * @returns the name of this class
  87332. */
  87333. WebVRFreeCamera.prototype.getClassName = function () {
  87334. return "WebVRFreeCamera";
  87335. };
  87336. /**
  87337. * Calls resetPose on the vrDisplay
  87338. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  87339. */
  87340. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  87341. //uses the vrDisplay's "resetPose()".
  87342. //pitch and roll won't be affected.
  87343. this._vrDevice.resetPose();
  87344. };
  87345. /**
  87346. * Updates the rig cameras (left and right eye)
  87347. */
  87348. WebVRFreeCamera.prototype._updateRigCameras = function () {
  87349. var camLeft = this._rigCameras[0];
  87350. var camRight = this._rigCameras[1];
  87351. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87352. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87353. camLeft.position.copyFrom(this._deviceRoomPosition);
  87354. camRight.position.copyFrom(this._deviceRoomPosition);
  87355. };
  87356. /**
  87357. * Updates the cached values of the camera
  87358. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  87359. */
  87360. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  87361. var _this = this;
  87362. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  87363. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  87364. if (!this.updateCacheCalled) {
  87365. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  87366. this.updateCacheCalled = true;
  87367. this.update();
  87368. }
  87369. // Set working vector to the device position in room space rotated by the new rotation
  87370. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  87371. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  87372. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  87373. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  87374. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  87375. // Add translation from anchor position
  87376. this._deviceToWorld.getTranslationToRef(this._workingVector);
  87377. this._workingVector.addInPlace(this.position);
  87378. this._workingVector.subtractInPlace(this._cache.position);
  87379. this._deviceToWorld.setTranslation(this._workingVector);
  87380. // Set an inverted matrix to be used when updating the camera
  87381. this._deviceToWorld.invertToRef(this._worldToDevice);
  87382. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  87383. this.controllers.forEach(function (controller) {
  87384. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  87385. controller.update();
  87386. });
  87387. }
  87388. if (!ignoreParentClass) {
  87389. _super.prototype._updateCache.call(this);
  87390. }
  87391. this.updateCacheCalled = false;
  87392. };
  87393. /**
  87394. * Updates the current device position and rotation in the babylon world
  87395. */
  87396. WebVRFreeCamera.prototype.update = function () {
  87397. // Get current device position in babylon world
  87398. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  87399. // Get current device rotation in babylon world
  87400. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  87401. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  87402. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  87403. _super.prototype.update.call(this);
  87404. };
  87405. /**
  87406. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  87407. * @returns an identity matrix
  87408. */
  87409. WebVRFreeCamera.prototype._getViewMatrix = function () {
  87410. return BABYLON.Matrix.Identity();
  87411. };
  87412. /**
  87413. * This function is called by the two RIG cameras.
  87414. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  87415. */
  87416. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  87417. var _this = this;
  87418. // Update the parent camera prior to using a child camera to avoid desynchronization
  87419. var parentCamera = this._cameraRigParams["parentCamera"];
  87420. parentCamera._updateCache();
  87421. //WebVR 1.1
  87422. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  87423. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  87424. if (!this.getScene().useRightHandedSystem) {
  87425. [2, 6, 8, 9, 14].forEach(function (num) {
  87426. _this._webvrViewMatrix.m[num] *= -1;
  87427. });
  87428. }
  87429. // update the camera rotation matrix
  87430. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  87431. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  87432. // Computing target and final matrix
  87433. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  87434. // should the view matrix be updated with scale and position offset?
  87435. if (parentCamera.deviceScaleFactor !== 1) {
  87436. this._webvrViewMatrix.invert();
  87437. // scale the position, if set
  87438. if (parentCamera.deviceScaleFactor) {
  87439. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  87440. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  87441. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  87442. }
  87443. this._webvrViewMatrix.invert();
  87444. }
  87445. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  87446. // Compute global position
  87447. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  87448. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  87449. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  87450. this._workingMatrix.getTranslationToRef(this._globalPosition);
  87451. this._markSyncedWithParent();
  87452. return this._webvrViewMatrix;
  87453. };
  87454. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  87455. var _this = this;
  87456. var parentCamera = this.parent;
  87457. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  87458. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  87459. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  87460. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  87461. //babylon compatible matrix
  87462. if (!this.getScene().useRightHandedSystem) {
  87463. [8, 9, 10, 11].forEach(function (num) {
  87464. _this._projectionMatrix.m[num] *= -1;
  87465. });
  87466. }
  87467. return this._projectionMatrix;
  87468. };
  87469. /**
  87470. * Initializes the controllers and their meshes
  87471. */
  87472. WebVRFreeCamera.prototype.initControllers = function () {
  87473. var _this = this;
  87474. this.controllers = [];
  87475. var manager = this.getScene().gamepadManager;
  87476. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  87477. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87478. var webVrController = gamepad;
  87479. if (webVrController.defaultModel) {
  87480. webVrController.defaultModel.setEnabled(false);
  87481. }
  87482. if (webVrController.hand === "right") {
  87483. _this._rightController = null;
  87484. }
  87485. if (webVrController.hand === "left") {
  87486. _this._leftController = null;
  87487. }
  87488. var controllerIndex = _this.controllers.indexOf(webVrController);
  87489. if (controllerIndex !== -1) {
  87490. _this.controllers.splice(controllerIndex, 1);
  87491. }
  87492. }
  87493. });
  87494. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  87495. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87496. var webVrController_1 = gamepad;
  87497. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  87498. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  87499. if (_this.webVROptions.controllerMeshes) {
  87500. if (webVrController_1.defaultModel) {
  87501. webVrController_1.defaultModel.setEnabled(true);
  87502. }
  87503. else {
  87504. // Load the meshes
  87505. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  87506. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  87507. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  87508. if (_this.webVROptions.defaultLightingOnControllers) {
  87509. if (!_this._lightOnControllers) {
  87510. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  87511. }
  87512. var activateLightOnSubMeshes_1 = function (mesh, light) {
  87513. var children = mesh.getChildren();
  87514. if (children.length !== 0) {
  87515. children.forEach(function (mesh) {
  87516. light.includedOnlyMeshes.push(mesh);
  87517. activateLightOnSubMeshes_1(mesh, light);
  87518. });
  87519. }
  87520. };
  87521. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  87522. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  87523. }
  87524. });
  87525. }
  87526. }
  87527. webVrController_1.attachToPoseControlledCamera(_this);
  87528. // since this is async - sanity check. Is the controller already stored?
  87529. if (_this.controllers.indexOf(webVrController_1) === -1) {
  87530. //add to the controllers array
  87531. _this.controllers.push(webVrController_1);
  87532. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  87533. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  87534. // So we're overriding setting left & right manually to be sure
  87535. var firstViveWandDetected = false;
  87536. for (var i = 0; i < _this.controllers.length; i++) {
  87537. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87538. if (!firstViveWandDetected) {
  87539. firstViveWandDetected = true;
  87540. _this.controllers[i].hand = "left";
  87541. }
  87542. else {
  87543. _this.controllers[i].hand = "right";
  87544. }
  87545. }
  87546. }
  87547. //did we find enough controllers? Great! let the developer know.
  87548. if (_this.controllers.length >= 2) {
  87549. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  87550. }
  87551. }
  87552. }
  87553. });
  87554. };
  87555. return WebVRFreeCamera;
  87556. }(BABYLON.FreeCamera));
  87557. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87558. })(BABYLON || (BABYLON = {}));
  87559. //# sourceMappingURL=babylon.webVRCamera.js.map
  87560. var BABYLON;
  87561. (function (BABYLON) {
  87562. // We're mainly based on the logic defined into the FreeCamera code
  87563. /**
  87564. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87565. * being tilted forward or back and left or right.
  87566. */
  87567. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87568. __extends(DeviceOrientationCamera, _super);
  87569. /**
  87570. * Creates a new device orientation camera
  87571. * @param name The name of the camera
  87572. * @param position The start position camera
  87573. * @param scene The scene the camera belongs to
  87574. */
  87575. function DeviceOrientationCamera(name, position, scene) {
  87576. var _this = _super.call(this, name, position, scene) || this;
  87577. _this._quaternionCache = new BABYLON.Quaternion();
  87578. _this.inputs.addDeviceOrientation();
  87579. return _this;
  87580. }
  87581. /**
  87582. * Gets the current instance class name ("DeviceOrientationCamera").
  87583. * This helps avoiding instanceof at run time.
  87584. * @returns the class name
  87585. */
  87586. DeviceOrientationCamera.prototype.getClassName = function () {
  87587. return "DeviceOrientationCamera";
  87588. };
  87589. /**
  87590. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87591. */
  87592. DeviceOrientationCamera.prototype._checkInputs = function () {
  87593. _super.prototype._checkInputs.call(this);
  87594. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87595. if (this._initialQuaternion) {
  87596. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87597. }
  87598. };
  87599. /**
  87600. * Reset the camera to its default orientation on the specified axis only.
  87601. * @param axis The axis to reset
  87602. */
  87603. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87604. var _this = this;
  87605. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87606. //can only work if this camera has a rotation quaternion already.
  87607. if (!this.rotationQuaternion)
  87608. return;
  87609. if (!this._initialQuaternion) {
  87610. this._initialQuaternion = new BABYLON.Quaternion();
  87611. }
  87612. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87613. ['x', 'y', 'z'].forEach(function (axisName) {
  87614. if (!axis[axisName]) {
  87615. _this._initialQuaternion[axisName] = 0;
  87616. }
  87617. else {
  87618. _this._initialQuaternion[axisName] *= -1;
  87619. }
  87620. });
  87621. this._initialQuaternion.normalize();
  87622. //force rotation update
  87623. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87624. };
  87625. return DeviceOrientationCamera;
  87626. }(BABYLON.FreeCamera));
  87627. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87628. })(BABYLON || (BABYLON = {}));
  87629. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87630. var BABYLON;
  87631. (function (BABYLON) {
  87632. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87633. __extends(VRDeviceOrientationFreeCamera, _super);
  87634. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87635. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87636. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87637. var _this = _super.call(this, name, position, scene) || this;
  87638. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87639. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87640. return _this;
  87641. }
  87642. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87643. return "VRDeviceOrientationFreeCamera";
  87644. };
  87645. return VRDeviceOrientationFreeCamera;
  87646. }(BABYLON.DeviceOrientationCamera));
  87647. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87648. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87649. __extends(VRDeviceOrientationGamepadCamera, _super);
  87650. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87651. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87652. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87653. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87654. _this.inputs.addGamepad();
  87655. return _this;
  87656. }
  87657. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87658. return "VRDeviceOrientationGamepadCamera";
  87659. };
  87660. return VRDeviceOrientationGamepadCamera;
  87661. }(VRDeviceOrientationFreeCamera));
  87662. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87663. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87664. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87665. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87666. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87667. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87668. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87669. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87670. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87671. _this.inputs.addVRDeviceOrientation();
  87672. return _this;
  87673. }
  87674. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87675. return "VRDeviceOrientationArcRotateCamera";
  87676. };
  87677. return VRDeviceOrientationArcRotateCamera;
  87678. }(BABYLON.ArcRotateCamera));
  87679. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87680. })(BABYLON || (BABYLON = {}));
  87681. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87682. var BABYLON;
  87683. (function (BABYLON) {
  87684. /**
  87685. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87686. */
  87687. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87688. __extends(AnaglyphFreeCamera, _super);
  87689. /**
  87690. * Creates a new AnaglyphFreeCamera
  87691. * @param name defines camera name
  87692. * @param position defines initial position
  87693. * @param interaxialDistance defines distance between each color axis
  87694. * @param scene defines the hosting scene
  87695. */
  87696. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87697. var _this = _super.call(this, name, position, scene) || this;
  87698. _this.interaxialDistance = interaxialDistance;
  87699. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87700. return _this;
  87701. }
  87702. /**
  87703. * Gets camera class name
  87704. * @returns AnaglyphFreeCamera
  87705. */
  87706. AnaglyphFreeCamera.prototype.getClassName = function () {
  87707. return "AnaglyphFreeCamera";
  87708. };
  87709. return AnaglyphFreeCamera;
  87710. }(BABYLON.FreeCamera));
  87711. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87712. /**
  87713. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87714. */
  87715. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87716. __extends(AnaglyphArcRotateCamera, _super);
  87717. /**
  87718. * Creates a new AnaglyphArcRotateCamera
  87719. * @param name defines camera name
  87720. * @param alpha defines alpha angle (in radians)
  87721. * @param beta defines beta angle (in radians)
  87722. * @param radius defines radius
  87723. * @param target defines camera target
  87724. * @param interaxialDistance defines distance between each color axis
  87725. * @param scene defines the hosting scene
  87726. */
  87727. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87728. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87729. _this.interaxialDistance = interaxialDistance;
  87730. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87731. return _this;
  87732. }
  87733. /**
  87734. * Gets camera class name
  87735. * @returns AnaglyphArcRotateCamera
  87736. */
  87737. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87738. return "AnaglyphArcRotateCamera";
  87739. };
  87740. return AnaglyphArcRotateCamera;
  87741. }(BABYLON.ArcRotateCamera));
  87742. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87743. /**
  87744. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87745. */
  87746. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87747. __extends(AnaglyphGamepadCamera, _super);
  87748. /**
  87749. * Creates a new AnaglyphGamepadCamera
  87750. * @param name defines camera name
  87751. * @param position defines initial position
  87752. * @param interaxialDistance defines distance between each color axis
  87753. * @param scene defines the hosting scene
  87754. */
  87755. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87756. var _this = _super.call(this, name, position, scene) || this;
  87757. _this.interaxialDistance = interaxialDistance;
  87758. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87759. return _this;
  87760. }
  87761. /**
  87762. * Gets camera class name
  87763. * @returns AnaglyphGamepadCamera
  87764. */
  87765. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87766. return "AnaglyphGamepadCamera";
  87767. };
  87768. return AnaglyphGamepadCamera;
  87769. }(BABYLON.GamepadCamera));
  87770. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87771. /**
  87772. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87773. */
  87774. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87775. __extends(AnaglyphUniversalCamera, _super);
  87776. /**
  87777. * Creates a new AnaglyphUniversalCamera
  87778. * @param name defines camera name
  87779. * @param position defines initial position
  87780. * @param interaxialDistance defines distance between each color axis
  87781. * @param scene defines the hosting scene
  87782. */
  87783. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87784. var _this = _super.call(this, name, position, scene) || this;
  87785. _this.interaxialDistance = interaxialDistance;
  87786. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87787. return _this;
  87788. }
  87789. /**
  87790. * Gets camera class name
  87791. * @returns AnaglyphUniversalCamera
  87792. */
  87793. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87794. return "AnaglyphUniversalCamera";
  87795. };
  87796. return AnaglyphUniversalCamera;
  87797. }(BABYLON.UniversalCamera));
  87798. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87799. /**
  87800. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87801. */
  87802. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87803. __extends(StereoscopicFreeCamera, _super);
  87804. /**
  87805. * Creates a new StereoscopicFreeCamera
  87806. * @param name defines camera name
  87807. * @param position defines initial position
  87808. * @param interaxialDistance defines distance between each color axis
  87809. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87810. * @param scene defines the hosting scene
  87811. */
  87812. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87813. var _this = _super.call(this, name, position, scene) || this;
  87814. _this.interaxialDistance = interaxialDistance;
  87815. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87816. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87817. return _this;
  87818. }
  87819. /**
  87820. * Gets camera class name
  87821. * @returns StereoscopicFreeCamera
  87822. */
  87823. StereoscopicFreeCamera.prototype.getClassName = function () {
  87824. return "StereoscopicFreeCamera";
  87825. };
  87826. return StereoscopicFreeCamera;
  87827. }(BABYLON.FreeCamera));
  87828. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87829. /**
  87830. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87831. */
  87832. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87833. __extends(StereoscopicArcRotateCamera, _super);
  87834. /**
  87835. * Creates a new StereoscopicArcRotateCamera
  87836. * @param name defines camera name
  87837. * @param alpha defines alpha angle (in radians)
  87838. * @param beta defines beta angle (in radians)
  87839. * @param radius defines radius
  87840. * @param target defines camera target
  87841. * @param interaxialDistance defines distance between each color axis
  87842. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87843. * @param scene defines the hosting scene
  87844. */
  87845. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87846. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87847. _this.interaxialDistance = interaxialDistance;
  87848. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87849. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87850. return _this;
  87851. }
  87852. /**
  87853. * Gets camera class name
  87854. * @returns StereoscopicArcRotateCamera
  87855. */
  87856. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87857. return "StereoscopicArcRotateCamera";
  87858. };
  87859. return StereoscopicArcRotateCamera;
  87860. }(BABYLON.ArcRotateCamera));
  87861. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87862. /**
  87863. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87864. */
  87865. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87866. __extends(StereoscopicGamepadCamera, _super);
  87867. /**
  87868. * Creates a new StereoscopicGamepadCamera
  87869. * @param name defines camera name
  87870. * @param position defines initial position
  87871. * @param interaxialDistance defines distance between each color axis
  87872. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87873. * @param scene defines the hosting scene
  87874. */
  87875. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87876. var _this = _super.call(this, name, position, scene) || this;
  87877. _this.interaxialDistance = interaxialDistance;
  87878. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87879. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87880. return _this;
  87881. }
  87882. /**
  87883. * Gets camera class name
  87884. * @returns StereoscopicGamepadCamera
  87885. */
  87886. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87887. return "StereoscopicGamepadCamera";
  87888. };
  87889. return StereoscopicGamepadCamera;
  87890. }(BABYLON.GamepadCamera));
  87891. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87892. /**
  87893. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87894. */
  87895. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87896. __extends(StereoscopicUniversalCamera, _super);
  87897. /**
  87898. * Creates a new StereoscopicUniversalCamera
  87899. * @param name defines camera name
  87900. * @param position defines initial position
  87901. * @param interaxialDistance defines distance between each color axis
  87902. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87903. * @param scene defines the hosting scene
  87904. */
  87905. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87906. var _this = _super.call(this, name, position, scene) || this;
  87907. _this.interaxialDistance = interaxialDistance;
  87908. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87909. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87910. return _this;
  87911. }
  87912. /**
  87913. * Gets camera class name
  87914. * @returns StereoscopicUniversalCamera
  87915. */
  87916. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87917. return "StereoscopicUniversalCamera";
  87918. };
  87919. return StereoscopicUniversalCamera;
  87920. }(BABYLON.UniversalCamera));
  87921. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87922. })(BABYLON || (BABYLON = {}));
  87923. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87924. var BABYLON;
  87925. (function (BABYLON) {
  87926. var VRExperienceHelperGazer = /** @class */ (function () {
  87927. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87928. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87929. this.scene = scene;
  87930. this._pointerDownOnMeshAsked = false;
  87931. this._isActionableMesh = false;
  87932. this._teleportationRequestInitiated = false;
  87933. this._teleportationBackRequestInitiated = false;
  87934. this._rotationRightAsked = false;
  87935. this._rotationLeftAsked = false;
  87936. this._dpadPressed = true;
  87937. this._activePointer = false;
  87938. this._id = VRExperienceHelperGazer._idCounter++;
  87939. // Gaze tracker
  87940. if (!gazeTrackerToClone) {
  87941. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87942. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87943. this._gazeTracker.isPickable = false;
  87944. this._gazeTracker.isVisible = false;
  87945. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87946. targetMat.specularColor = BABYLON.Color3.Black();
  87947. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87948. targetMat.backFaceCulling = false;
  87949. this._gazeTracker.material = targetMat;
  87950. }
  87951. else {
  87952. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87953. }
  87954. }
  87955. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87956. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87957. };
  87958. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87959. this._pointerDownOnMeshAsked = true;
  87960. if (this._currentMeshSelected && this._currentHit) {
  87961. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87962. }
  87963. };
  87964. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87965. if (this._currentMeshSelected && this._currentHit) {
  87966. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87967. }
  87968. this._pointerDownOnMeshAsked = false;
  87969. };
  87970. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87971. this._activePointer = true;
  87972. };
  87973. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87974. this._activePointer = false;
  87975. };
  87976. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87977. if (distance === void 0) { distance = 100; }
  87978. };
  87979. VRExperienceHelperGazer.prototype.dispose = function () {
  87980. this._interactionsEnabled = false;
  87981. this._teleportationEnabled = false;
  87982. if (this._gazeTracker) {
  87983. this._gazeTracker.dispose();
  87984. }
  87985. };
  87986. VRExperienceHelperGazer._idCounter = 0;
  87987. return VRExperienceHelperGazer;
  87988. }());
  87989. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87990. __extends(VRExperienceHelperControllerGazer, _super);
  87991. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87992. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87993. _this.webVRController = webVRController;
  87994. // Laser pointer
  87995. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87996. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87997. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87998. laserPointerMaterial.alpha = 0.6;
  87999. _this._laserPointer.material = laserPointerMaterial;
  88000. _this._laserPointer.rotation.x = Math.PI / 2;
  88001. _this._laserPointer.position.z = -0.5;
  88002. _this._laserPointer.isVisible = false;
  88003. if (!webVRController.mesh) {
  88004. // Create an empty mesh that is used prior to loading the high quality model
  88005. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  88006. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  88007. preloadPointerPose.rotation.x = -0.7;
  88008. preloadMesh.addChild(preloadPointerPose);
  88009. webVRController.attachToMesh(preloadMesh);
  88010. }
  88011. _this._setLaserPointerParent(webVRController.mesh);
  88012. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  88013. _this._setLaserPointerParent(mesh);
  88014. });
  88015. return _this;
  88016. }
  88017. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  88018. return this.webVRController.getForwardRay(length);
  88019. };
  88020. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  88021. _super.prototype._activatePointer.call(this);
  88022. this._laserPointer.isVisible = true;
  88023. };
  88024. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  88025. _super.prototype._deactivatePointer.call(this);
  88026. this._laserPointer.isVisible = false;
  88027. };
  88028. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  88029. this._laserPointer.material.emissiveColor = color;
  88030. };
  88031. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  88032. var makeNotPick = function (root) {
  88033. root.name += " laserPointer";
  88034. root.getChildMeshes().forEach(function (c) {
  88035. makeNotPick(c);
  88036. });
  88037. };
  88038. makeNotPick(mesh);
  88039. var childMeshes = mesh.getChildMeshes();
  88040. this.webVRController._pointingPoseNode = null;
  88041. for (var i = 0; i < childMeshes.length; i++) {
  88042. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  88043. mesh = childMeshes[i];
  88044. this.webVRController._pointingPoseNode = mesh;
  88045. break;
  88046. }
  88047. }
  88048. this._laserPointer.parent = mesh;
  88049. };
  88050. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  88051. if (distance === void 0) { distance = 100; }
  88052. this._laserPointer.scaling.y = distance;
  88053. this._laserPointer.position.z = -distance / 2;
  88054. };
  88055. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  88056. _super.prototype.dispose.call(this);
  88057. this._laserPointer.dispose();
  88058. if (this._meshAttachedObserver) {
  88059. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  88060. }
  88061. };
  88062. return VRExperienceHelperControllerGazer;
  88063. }(VRExperienceHelperGazer));
  88064. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  88065. __extends(VRExperienceHelperCameraGazer, _super);
  88066. function VRExperienceHelperCameraGazer(getCamera, scene) {
  88067. var _this = _super.call(this, scene) || this;
  88068. _this.getCamera = getCamera;
  88069. return _this;
  88070. }
  88071. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  88072. var camera = this.getCamera();
  88073. if (camera) {
  88074. return camera.getForwardRay(length);
  88075. }
  88076. else {
  88077. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  88078. }
  88079. };
  88080. return VRExperienceHelperCameraGazer;
  88081. }(VRExperienceHelperGazer));
  88082. /**
  88083. * Helps to quickly add VR support to an existing scene.
  88084. * See http://doc.babylonjs.com/how_to/webvr_helper
  88085. */
  88086. var VRExperienceHelper = /** @class */ (function () {
  88087. /**
  88088. * Instantiates a VRExperienceHelper.
  88089. * Helps to quickly add VR support to an existing scene.
  88090. * @param scene The scene the VRExperienceHelper belongs to.
  88091. * @param webVROptions Options to modify the vr experience helper's behavior.
  88092. */
  88093. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  88094. if (webVROptions === void 0) { webVROptions = {}; }
  88095. var _this = this;
  88096. this.webVROptions = webVROptions;
  88097. // Can the system support WebVR, even if a headset isn't plugged in?
  88098. this._webVRsupported = false;
  88099. // If WebVR is supported, is a headset plugged in and are we ready to present?
  88100. this._webVRready = false;
  88101. // Are we waiting for the requestPresent callback to complete?
  88102. this._webVRrequesting = false;
  88103. // Are we presenting to the headset right now?
  88104. this._webVRpresenting = false;
  88105. // Are we presenting in the fullscreen fallback?
  88106. this._fullscreenVRpresenting = false;
  88107. /**
  88108. * Observable raised when entering VR.
  88109. */
  88110. this.onEnteringVRObservable = new BABYLON.Observable();
  88111. /**
  88112. * Observable raised when exiting VR.
  88113. */
  88114. this.onExitingVRObservable = new BABYLON.Observable();
  88115. /**
  88116. * Observable raised when controller mesh is loaded.
  88117. */
  88118. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  88119. this._useCustomVRButton = false;
  88120. this._teleportationRequested = false;
  88121. this._teleportActive = false;
  88122. this._floorMeshesCollection = [];
  88123. this._rotationAllowed = true;
  88124. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  88125. this._isDefaultTeleportationTarget = true;
  88126. this._teleportationFillColor = "#444444";
  88127. this._teleportationBorderColor = "#FFFFFF";
  88128. this._rotationAngle = 0;
  88129. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  88130. this._padSensibilityUp = 0.65;
  88131. this._padSensibilityDown = 0.35;
  88132. this.leftController = null;
  88133. this.rightController = null;
  88134. /**
  88135. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  88136. */
  88137. this.onNewMeshSelected = new BABYLON.Observable();
  88138. /**
  88139. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  88140. */
  88141. this.onNewMeshPicked = new BABYLON.Observable();
  88142. /**
  88143. * Observable raised before camera teleportation
  88144. */
  88145. this.onBeforeCameraTeleport = new BABYLON.Observable();
  88146. /**
  88147. * Observable raised after camera teleportation
  88148. */
  88149. this.onAfterCameraTeleport = new BABYLON.Observable();
  88150. /**
  88151. * Observable raised when current selected mesh gets unselected
  88152. */
  88153. this.onSelectedMeshUnselected = new BABYLON.Observable();
  88154. /**
  88155. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  88156. */
  88157. this.teleportationEnabled = true;
  88158. this._teleportationInitialized = false;
  88159. this._interactionsEnabled = false;
  88160. this._interactionsRequested = false;
  88161. this._displayGaze = true;
  88162. this._displayLaserPointer = true;
  88163. this._onResize = function () {
  88164. _this.moveButtonToBottomRight();
  88165. if (_this._fullscreenVRpresenting && _this._webVRready) {
  88166. _this.exitVR();
  88167. }
  88168. };
  88169. this._onFullscreenChange = function () {
  88170. if (document.fullscreen !== undefined) {
  88171. _this._fullscreenVRpresenting = document.fullscreen;
  88172. }
  88173. else if (document.mozFullScreen !== undefined) {
  88174. _this._fullscreenVRpresenting = document.mozFullScreen;
  88175. }
  88176. else if (document.webkitIsFullScreen !== undefined) {
  88177. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  88178. }
  88179. else if (document.msIsFullScreen !== undefined) {
  88180. _this._fullscreenVRpresenting = document.msIsFullScreen;
  88181. }
  88182. if (!_this._fullscreenVRpresenting && _this._canvas) {
  88183. _this.exitVR();
  88184. if (!_this._useCustomVRButton) {
  88185. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  88186. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  88187. }
  88188. }
  88189. };
  88190. this.beforeRender = function () {
  88191. if (_this.leftController && _this.leftController._activePointer) {
  88192. _this._castRayAndSelectObject(_this.leftController);
  88193. }
  88194. if (_this.rightController && _this.rightController._activePointer) {
  88195. _this._castRayAndSelectObject(_this.rightController);
  88196. }
  88197. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  88198. _this._castRayAndSelectObject(_this._cameraGazer);
  88199. }
  88200. else {
  88201. _this._cameraGazer._gazeTracker.isVisible = false;
  88202. }
  88203. };
  88204. this._onNewGamepadConnected = function (gamepad) {
  88205. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  88206. if (gamepad.leftStick) {
  88207. gamepad.onleftstickchanged(function (stickValues) {
  88208. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  88209. // Listening to classic/xbox gamepad only if no VR controller is active
  88210. if ((!_this.leftController && !_this.rightController) ||
  88211. ((_this.leftController && !_this.leftController._activePointer) &&
  88212. (_this.rightController && !_this.rightController._activePointer))) {
  88213. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  88214. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  88215. }
  88216. }
  88217. });
  88218. }
  88219. if (gamepad.rightStick) {
  88220. gamepad.onrightstickchanged(function (stickValues) {
  88221. if (_this._teleportationInitialized) {
  88222. _this._checkRotate(stickValues, _this._cameraGazer);
  88223. }
  88224. });
  88225. }
  88226. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  88227. gamepad.onbuttondown(function (buttonPressed) {
  88228. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  88229. _this._cameraGazer._selectionPointerDown();
  88230. }
  88231. });
  88232. gamepad.onbuttonup(function (buttonPressed) {
  88233. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  88234. _this._cameraGazer._selectionPointerUp();
  88235. }
  88236. });
  88237. }
  88238. }
  88239. else {
  88240. var webVRController = gamepad;
  88241. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  88242. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  88243. _this.rightController = controller;
  88244. }
  88245. else {
  88246. _this.leftController = controller;
  88247. }
  88248. _this._tryEnableInteractionOnController(controller);
  88249. }
  88250. };
  88251. // 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
  88252. this._tryEnableInteractionOnController = function (controller) {
  88253. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  88254. _this._enableInteractionOnController(controller);
  88255. }
  88256. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  88257. _this._enableTeleportationOnController(controller);
  88258. }
  88259. };
  88260. this._onNewGamepadDisconnected = function (gamepad) {
  88261. if (gamepad instanceof BABYLON.WebVRController) {
  88262. if (gamepad.hand === "left" && _this.leftController != null) {
  88263. _this.leftController.dispose();
  88264. _this.leftController = null;
  88265. }
  88266. if (gamepad.hand === "right" && _this.rightController != null) {
  88267. _this.rightController.dispose();
  88268. _this.rightController = null;
  88269. }
  88270. }
  88271. };
  88272. this._workingVector = BABYLON.Vector3.Zero();
  88273. this._workingQuaternion = BABYLON.Quaternion.Identity();
  88274. this._workingMatrix = BABYLON.Matrix.Identity();
  88275. this._scene = scene;
  88276. this._canvas = scene.getEngine().getRenderingCanvas();
  88277. // Parse options
  88278. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  88279. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  88280. }
  88281. if (webVROptions.createDeviceOrientationCamera === undefined) {
  88282. webVROptions.createDeviceOrientationCamera = true;
  88283. }
  88284. if (webVROptions.laserToggle === undefined) {
  88285. webVROptions.laserToggle = true;
  88286. }
  88287. if (webVROptions.defaultHeight === undefined) {
  88288. webVROptions.defaultHeight = 1.7;
  88289. }
  88290. if (webVROptions.useCustomVRButton) {
  88291. this._useCustomVRButton = true;
  88292. if (webVROptions.customVRButton) {
  88293. this._btnVR = webVROptions.customVRButton;
  88294. }
  88295. }
  88296. if (webVROptions.rayLength) {
  88297. this._rayLength = webVROptions.rayLength;
  88298. }
  88299. this._defaultHeight = webVROptions.defaultHeight;
  88300. if (webVROptions.positionScale) {
  88301. this._rayLength *= webVROptions.positionScale;
  88302. this._defaultHeight *= webVROptions.positionScale;
  88303. }
  88304. // Set position
  88305. if (this._scene.activeCamera) {
  88306. this._position = this._scene.activeCamera.position.clone();
  88307. }
  88308. else {
  88309. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  88310. }
  88311. // Set non-vr camera
  88312. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  88313. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  88314. // Copy data from existing camera
  88315. if (this._scene.activeCamera) {
  88316. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88317. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  88318. // Set rotation from previous camera
  88319. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  88320. var targetCamera = this._scene.activeCamera;
  88321. if (targetCamera.rotationQuaternion) {
  88322. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  88323. }
  88324. else {
  88325. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  88326. }
  88327. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  88328. }
  88329. }
  88330. this._scene.activeCamera = this._deviceOrientationCamera;
  88331. if (this._canvas) {
  88332. this._scene.activeCamera.attachControl(this._canvas);
  88333. }
  88334. }
  88335. else {
  88336. this._existingCamera = this._scene.activeCamera;
  88337. }
  88338. // Create VR cameras
  88339. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88340. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  88341. }
  88342. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  88343. this._webVRCamera.useStandingMatrix();
  88344. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  88345. // Create default button
  88346. if (!this._useCustomVRButton) {
  88347. this._btnVR = document.createElement("BUTTON");
  88348. this._btnVR.className = "babylonVRicon";
  88349. this._btnVR.id = "babylonVRiconbtn";
  88350. this._btnVR.title = "Click to switch to VR";
  88351. 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) }";
  88352. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  88353. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  88354. // css += ".babylonVRicon.vrdisplaysupported { }";
  88355. // css += ".babylonVRicon.vrdisplayready { }";
  88356. // css += ".babylonVRicon.vrdisplayrequesting { }";
  88357. var style = document.createElement('style');
  88358. style.appendChild(document.createTextNode(css));
  88359. document.getElementsByTagName('head')[0].appendChild(style);
  88360. this.moveButtonToBottomRight();
  88361. }
  88362. // VR button click event
  88363. if (this._btnVR) {
  88364. this._btnVR.addEventListener("click", function () {
  88365. if (!_this.isInVRMode) {
  88366. _this.enterVR();
  88367. }
  88368. else {
  88369. _this.exitVR();
  88370. }
  88371. });
  88372. }
  88373. // Window events
  88374. window.addEventListener("resize", this._onResize);
  88375. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  88376. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  88377. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  88378. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  88379. // Display vr button when headset is connected
  88380. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88381. this.displayVRButton();
  88382. }
  88383. else {
  88384. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  88385. if (e.vrDisplay) {
  88386. _this.displayVRButton();
  88387. }
  88388. });
  88389. }
  88390. // Exiting VR mode using 'ESC' key on desktop
  88391. this._onKeyDown = function (event) {
  88392. if (event.keyCode === 27 && _this.isInVRMode) {
  88393. _this.exitVR();
  88394. }
  88395. };
  88396. document.addEventListener("keydown", this._onKeyDown);
  88397. // Exiting VR mode double tapping the touch screen
  88398. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  88399. if (_this.isInVRMode) {
  88400. _this.exitVR();
  88401. if (_this._fullscreenVRpresenting) {
  88402. _this._scene.getEngine().switchFullscreen(true);
  88403. }
  88404. }
  88405. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  88406. // Listen for WebVR display changes
  88407. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  88408. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  88409. this._onVRRequestPresentStart = function () {
  88410. _this._webVRrequesting = true;
  88411. _this.updateButtonVisibility();
  88412. };
  88413. this._onVRRequestPresentComplete = function (success) {
  88414. _this._webVRrequesting = false;
  88415. _this.updateButtonVisibility();
  88416. };
  88417. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  88418. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  88419. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  88420. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88421. scene.onDisposeObservable.add(function () {
  88422. _this.dispose();
  88423. });
  88424. // Gamepad connection events
  88425. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  88426. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  88427. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  88428. this.updateButtonVisibility();
  88429. //create easing functions
  88430. this._circleEase = new BABYLON.CircleEase();
  88431. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88432. if (this.webVROptions.floorMeshes) {
  88433. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  88434. }
  88435. }
  88436. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  88437. /** Return this.onEnteringVRObservable
  88438. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  88439. */
  88440. get: function () {
  88441. return this.onEnteringVRObservable;
  88442. },
  88443. enumerable: true,
  88444. configurable: true
  88445. });
  88446. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  88447. /** Return this.onExitingVRObservable
  88448. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  88449. */
  88450. get: function () {
  88451. return this.onExitingVRObservable;
  88452. },
  88453. enumerable: true,
  88454. configurable: true
  88455. });
  88456. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  88457. /** Return this.onControllerMeshLoadedObservable
  88458. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  88459. */
  88460. get: function () {
  88461. return this.onControllerMeshLoadedObservable;
  88462. },
  88463. enumerable: true,
  88464. configurable: true
  88465. });
  88466. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  88467. /**
  88468. * The mesh used to display where the user is going to teleport.
  88469. */
  88470. get: function () {
  88471. return this._teleportationTarget;
  88472. },
  88473. /**
  88474. * Sets the mesh to be used to display where the user is going to teleport.
  88475. */
  88476. set: function (value) {
  88477. if (value) {
  88478. value.name = "teleportationTarget";
  88479. this._isDefaultTeleportationTarget = false;
  88480. this._teleportationTarget = value;
  88481. }
  88482. },
  88483. enumerable: true,
  88484. configurable: true
  88485. });
  88486. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  88487. /**
  88488. * The mesh used to display where the user is selecting,
  88489. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  88490. * See http://doc.babylonjs.com/resources/baking_transformations
  88491. */
  88492. get: function () {
  88493. return this._cameraGazer._gazeTracker;
  88494. },
  88495. set: function (value) {
  88496. if (value) {
  88497. this._cameraGazer._gazeTracker = value;
  88498. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  88499. this._cameraGazer._gazeTracker.isPickable = false;
  88500. this._cameraGazer._gazeTracker.isVisible = false;
  88501. this._cameraGazer._gazeTracker.name = "gazeTracker";
  88502. if (this.leftController) {
  88503. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88504. }
  88505. if (this.rightController) {
  88506. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88507. }
  88508. }
  88509. },
  88510. enumerable: true,
  88511. configurable: true
  88512. });
  88513. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  88514. /**
  88515. * If the ray of the gaze should be displayed.
  88516. */
  88517. get: function () {
  88518. return this._displayGaze;
  88519. },
  88520. /**
  88521. * Sets if the ray of the gaze should be displayed.
  88522. */
  88523. set: function (value) {
  88524. this._displayGaze = value;
  88525. if (!value) {
  88526. this._cameraGazer._gazeTracker.isVisible = false;
  88527. if (this.leftController) {
  88528. this.leftController._gazeTracker.isVisible = false;
  88529. }
  88530. if (this.rightController) {
  88531. this.rightController._gazeTracker.isVisible = false;
  88532. }
  88533. }
  88534. },
  88535. enumerable: true,
  88536. configurable: true
  88537. });
  88538. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  88539. /**
  88540. * If the ray of the LaserPointer should be displayed.
  88541. */
  88542. get: function () {
  88543. return this._displayLaserPointer;
  88544. },
  88545. /**
  88546. * Sets if the ray of the LaserPointer should be displayed.
  88547. */
  88548. set: function (value) {
  88549. this._displayLaserPointer = value;
  88550. if (!value) {
  88551. if (this.rightController) {
  88552. this.rightController._deactivatePointer();
  88553. this.rightController._gazeTracker.isVisible = false;
  88554. }
  88555. if (this.leftController) {
  88556. this.leftController._deactivatePointer();
  88557. this.leftController._gazeTracker.isVisible = false;
  88558. }
  88559. }
  88560. else {
  88561. if (this.rightController) {
  88562. this.rightController._activatePointer();
  88563. }
  88564. if (this.leftController) {
  88565. this.leftController._activatePointer();
  88566. }
  88567. }
  88568. },
  88569. enumerable: true,
  88570. configurable: true
  88571. });
  88572. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88573. /**
  88574. * The deviceOrientationCamera used as the camera when not in VR.
  88575. */
  88576. get: function () {
  88577. return this._deviceOrientationCamera;
  88578. },
  88579. enumerable: true,
  88580. configurable: true
  88581. });
  88582. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88583. /**
  88584. * Based on the current WebVR support, returns the current VR camera used.
  88585. */
  88586. get: function () {
  88587. if (this._webVRready) {
  88588. return this._webVRCamera;
  88589. }
  88590. else {
  88591. return this._scene.activeCamera;
  88592. }
  88593. },
  88594. enumerable: true,
  88595. configurable: true
  88596. });
  88597. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88598. /**
  88599. * The webVRCamera which is used when in VR.
  88600. */
  88601. get: function () {
  88602. return this._webVRCamera;
  88603. },
  88604. enumerable: true,
  88605. configurable: true
  88606. });
  88607. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88608. /**
  88609. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88610. */
  88611. get: function () {
  88612. return this._vrDeviceOrientationCamera;
  88613. },
  88614. enumerable: true,
  88615. configurable: true
  88616. });
  88617. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88618. get: function () {
  88619. var result = this._cameraGazer._teleportationRequestInitiated
  88620. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88621. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88622. return result;
  88623. },
  88624. enumerable: true,
  88625. configurable: true
  88626. });
  88627. // Raised when one of the controller has loaded successfully its associated default mesh
  88628. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88629. if (this.leftController && this.leftController.webVRController == webVRController) {
  88630. if (webVRController.mesh) {
  88631. this.leftController._setLaserPointerParent(webVRController.mesh);
  88632. }
  88633. }
  88634. if (this.rightController && this.rightController.webVRController == webVRController) {
  88635. if (webVRController.mesh) {
  88636. this.rightController._setLaserPointerParent(webVRController.mesh);
  88637. }
  88638. }
  88639. try {
  88640. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88641. }
  88642. catch (err) {
  88643. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88644. }
  88645. };
  88646. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88647. /**
  88648. * Gets a value indicating if we are currently in VR mode.
  88649. */
  88650. get: function () {
  88651. return this._webVRpresenting || this._fullscreenVRpresenting;
  88652. },
  88653. enumerable: true,
  88654. configurable: true
  88655. });
  88656. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88657. var vrDisplay = this._scene.getEngine().getVRDevice();
  88658. if (vrDisplay) {
  88659. var wasPresenting = this._webVRpresenting;
  88660. // A VR display is connected
  88661. this._webVRpresenting = vrDisplay.isPresenting;
  88662. if (wasPresenting && !this._webVRpresenting)
  88663. this.exitVR();
  88664. }
  88665. else {
  88666. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88667. }
  88668. this.updateButtonVisibility();
  88669. };
  88670. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88671. this._webVRsupported = eventArgs.vrSupported;
  88672. this._webVRready = !!eventArgs.vrDisplay;
  88673. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88674. this.updateButtonVisibility();
  88675. };
  88676. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88677. if (this._canvas && !this._useCustomVRButton) {
  88678. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88679. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88680. }
  88681. };
  88682. VRExperienceHelper.prototype.displayVRButton = function () {
  88683. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88684. document.body.appendChild(this._btnVR);
  88685. this._btnVRDisplayed = true;
  88686. }
  88687. };
  88688. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88689. if (!this._btnVR || this._useCustomVRButton) {
  88690. return;
  88691. }
  88692. this._btnVR.className = "babylonVRicon";
  88693. if (this.isInVRMode) {
  88694. this._btnVR.className += " vrdisplaypresenting";
  88695. }
  88696. else {
  88697. if (this._webVRready)
  88698. this._btnVR.className += " vrdisplayready";
  88699. if (this._webVRsupported)
  88700. this._btnVR.className += " vrdisplaysupported";
  88701. if (this._webVRrequesting)
  88702. this._btnVR.className += " vrdisplayrequesting";
  88703. }
  88704. };
  88705. /**
  88706. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88707. * Otherwise, will use the fullscreen API.
  88708. */
  88709. VRExperienceHelper.prototype.enterVR = function () {
  88710. if (this.onEnteringVRObservable) {
  88711. try {
  88712. this.onEnteringVRObservable.notifyObservers(this);
  88713. }
  88714. catch (err) {
  88715. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88716. }
  88717. }
  88718. if (this._scene.activeCamera) {
  88719. this._position = this._scene.activeCamera.position.clone();
  88720. // make sure that we return to the last active camera
  88721. this._existingCamera = this._scene.activeCamera;
  88722. }
  88723. if (this._webVRrequesting)
  88724. return;
  88725. // If WebVR is supported and a headset is connected
  88726. if (this._webVRready) {
  88727. if (!this._webVRpresenting) {
  88728. this._webVRCamera.position = this._position;
  88729. this._scene.activeCamera = this._webVRCamera;
  88730. }
  88731. }
  88732. else if (this._vrDeviceOrientationCamera) {
  88733. this._vrDeviceOrientationCamera.position = this._position;
  88734. if (this._scene.activeCamera) {
  88735. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88736. }
  88737. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88738. this._scene.getEngine().switchFullscreen(true);
  88739. this.updateButtonVisibility();
  88740. }
  88741. if (this._scene.activeCamera && this._canvas) {
  88742. this._scene.activeCamera.attachControl(this._canvas);
  88743. }
  88744. if (this._interactionsEnabled) {
  88745. this._scene.registerBeforeRender(this.beforeRender);
  88746. }
  88747. };
  88748. /**
  88749. * Attempt to exit VR, or fullscreen.
  88750. */
  88751. VRExperienceHelper.prototype.exitVR = function () {
  88752. if (this.onExitingVRObservable) {
  88753. try {
  88754. this.onExitingVRObservable.notifyObservers(this);
  88755. }
  88756. catch (err) {
  88757. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88758. }
  88759. }
  88760. if (this._webVRpresenting) {
  88761. this._scene.getEngine().disableVR();
  88762. }
  88763. if (this._scene.activeCamera) {
  88764. this._position = this._scene.activeCamera.position.clone();
  88765. }
  88766. if (this._deviceOrientationCamera) {
  88767. this._deviceOrientationCamera.position = this._position;
  88768. this._scene.activeCamera = this._deviceOrientationCamera;
  88769. if (this._canvas) {
  88770. this._scene.activeCamera.attachControl(this._canvas);
  88771. }
  88772. }
  88773. else if (this._existingCamera) {
  88774. this._existingCamera.position = this._position;
  88775. this._scene.activeCamera = this._existingCamera;
  88776. }
  88777. this.updateButtonVisibility();
  88778. if (this._interactionsEnabled) {
  88779. this._scene.unregisterBeforeRender(this.beforeRender);
  88780. }
  88781. // resize to update width and height when exiting vr exits fullscreen
  88782. this._scene.getEngine().resize();
  88783. };
  88784. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88785. /**
  88786. * The position of the vr experience helper.
  88787. */
  88788. get: function () {
  88789. return this._position;
  88790. },
  88791. /**
  88792. * Sets the position of the vr experience helper.
  88793. */
  88794. set: function (value) {
  88795. this._position = value;
  88796. if (this._scene.activeCamera) {
  88797. this._scene.activeCamera.position = value;
  88798. }
  88799. },
  88800. enumerable: true,
  88801. configurable: true
  88802. });
  88803. /**
  88804. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88805. */
  88806. VRExperienceHelper.prototype.enableInteractions = function () {
  88807. var _this = this;
  88808. if (!this._interactionsEnabled) {
  88809. this._interactionsRequested = true;
  88810. if (this.leftController) {
  88811. this._enableInteractionOnController(this.leftController);
  88812. }
  88813. if (this.rightController) {
  88814. this._enableInteractionOnController(this.rightController);
  88815. }
  88816. this.raySelectionPredicate = function (mesh) {
  88817. return mesh.isVisible;
  88818. };
  88819. this.meshSelectionPredicate = function (mesh) {
  88820. return true;
  88821. };
  88822. this._raySelectionPredicate = function (mesh) {
  88823. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88824. && mesh.name.indexOf("teleportationTarget") === -1
  88825. && mesh.name.indexOf("torusTeleportation") === -1
  88826. && mesh.name.indexOf("laserPointer") === -1)) {
  88827. return _this.raySelectionPredicate(mesh);
  88828. }
  88829. return false;
  88830. };
  88831. this._interactionsEnabled = true;
  88832. }
  88833. };
  88834. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88835. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88836. if (this._floorMeshesCollection[i].id === mesh.id) {
  88837. return true;
  88838. }
  88839. }
  88840. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88841. return true;
  88842. }
  88843. return false;
  88844. };
  88845. /**
  88846. * Adds a floor mesh to be used for teleportation.
  88847. * @param floorMesh the mesh to be used for teleportation.
  88848. */
  88849. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88850. if (!this._floorMeshesCollection) {
  88851. return;
  88852. }
  88853. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88854. return;
  88855. }
  88856. this._floorMeshesCollection.push(floorMesh);
  88857. };
  88858. /**
  88859. * Removes a floor mesh from being used for teleportation.
  88860. * @param floorMesh the mesh to be removed.
  88861. */
  88862. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88863. if (!this._floorMeshesCollection) {
  88864. return;
  88865. }
  88866. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88867. if (meshIndex !== -1) {
  88868. this._floorMeshesCollection.splice(meshIndex, 1);
  88869. }
  88870. };
  88871. /**
  88872. * Enables interactions and teleportation using the VR controllers and gaze.
  88873. * @param vrTeleportationOptions options to modify teleportation behavior.
  88874. */
  88875. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88876. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88877. if (!this._teleportationInitialized) {
  88878. this._teleportationRequested = true;
  88879. this.enableInteractions();
  88880. if (vrTeleportationOptions.floorMeshName) {
  88881. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88882. }
  88883. if (vrTeleportationOptions.floorMeshes) {
  88884. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88885. }
  88886. if (this.leftController != null) {
  88887. this._enableTeleportationOnController(this.leftController);
  88888. }
  88889. if (this.rightController != null) {
  88890. this._enableTeleportationOnController(this.rightController);
  88891. }
  88892. // Creates an image processing post process for the vignette not relying
  88893. // on the main scene configuration for image processing to reduce setup and spaces
  88894. // (gamma/linear) conflicts.
  88895. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88896. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88897. imageProcessingConfiguration.vignetteEnabled = true;
  88898. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88899. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88900. this._teleportationInitialized = true;
  88901. if (this._isDefaultTeleportationTarget) {
  88902. this._createTeleportationCircles();
  88903. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88904. }
  88905. }
  88906. };
  88907. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88908. var _this = this;
  88909. var controllerMesh = controller.webVRController.mesh;
  88910. if (controllerMesh) {
  88911. controller._interactionsEnabled = true;
  88912. controller._activatePointer();
  88913. if (this.webVROptions.laserToggle) {
  88914. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88915. // Enabling / disabling laserPointer
  88916. if (_this._displayLaserPointer && stateObject.value === 1) {
  88917. if (controller._activePointer) {
  88918. controller._deactivatePointer();
  88919. }
  88920. else {
  88921. controller._activatePointer();
  88922. }
  88923. if (_this.displayGaze) {
  88924. controller._gazeTracker.isVisible = controller._activePointer;
  88925. }
  88926. }
  88927. });
  88928. }
  88929. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88930. if (!controller._pointerDownOnMeshAsked) {
  88931. if (stateObject.value > _this._padSensibilityUp) {
  88932. controller._selectionPointerDown();
  88933. }
  88934. }
  88935. else if (stateObject.value < _this._padSensibilityDown) {
  88936. controller._selectionPointerUp();
  88937. }
  88938. });
  88939. }
  88940. };
  88941. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88942. // Dont teleport if another gaze already requested teleportation
  88943. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88944. return;
  88945. }
  88946. if (!gazer._teleportationRequestInitiated) {
  88947. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88948. gazer._activatePointer();
  88949. gazer._teleportationRequestInitiated = true;
  88950. }
  88951. }
  88952. else {
  88953. // Listening to the proper controller values changes to confirm teleportation
  88954. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88955. if (this._teleportActive) {
  88956. this._teleportCamera(this._haloCenter);
  88957. }
  88958. gazer._teleportationRequestInitiated = false;
  88959. }
  88960. }
  88961. };
  88962. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88963. // Only rotate when user is not currently selecting a teleportation location
  88964. if (gazer._teleportationRequestInitiated) {
  88965. return;
  88966. }
  88967. if (!gazer._rotationLeftAsked) {
  88968. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88969. gazer._rotationLeftAsked = true;
  88970. if (this._rotationAllowed) {
  88971. this._rotateCamera(false);
  88972. }
  88973. }
  88974. }
  88975. else {
  88976. if (stateObject.x > -this._padSensibilityDown) {
  88977. gazer._rotationLeftAsked = false;
  88978. }
  88979. }
  88980. if (!gazer._rotationRightAsked) {
  88981. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88982. gazer._rotationRightAsked = true;
  88983. if (this._rotationAllowed) {
  88984. this._rotateCamera(true);
  88985. }
  88986. }
  88987. }
  88988. else {
  88989. if (stateObject.x < this._padSensibilityDown) {
  88990. gazer._rotationRightAsked = false;
  88991. }
  88992. }
  88993. };
  88994. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88995. // Only teleport backwards when user is not currently selecting a teleportation location
  88996. if (gazer._teleportationRequestInitiated) {
  88997. return;
  88998. }
  88999. // Teleport backwards
  89000. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  89001. if (!gazer._teleportationBackRequestInitiated) {
  89002. if (!this.currentVRCamera) {
  89003. return;
  89004. }
  89005. // Get rotation and position of the current camera
  89006. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  89007. var position = this.currentVRCamera.position;
  89008. // If the camera has device position, use that instead
  89009. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  89010. rotation = this.currentVRCamera.deviceRotationQuaternion;
  89011. position = this.currentVRCamera.devicePosition;
  89012. }
  89013. // Get matrix with only the y rotation of the device rotation
  89014. rotation.toEulerAnglesToRef(this._workingVector);
  89015. this._workingVector.z = 0;
  89016. this._workingVector.x = 0;
  89017. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  89018. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  89019. // Rotate backwards ray by device rotation to cast at the ground behind the user
  89020. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  89021. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  89022. var ray = new BABYLON.Ray(position, this._workingVector);
  89023. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89024. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  89025. this._teleportCamera(hit.pickedPoint);
  89026. }
  89027. gazer._teleportationBackRequestInitiated = true;
  89028. }
  89029. }
  89030. else {
  89031. gazer._teleportationBackRequestInitiated = false;
  89032. }
  89033. };
  89034. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  89035. var _this = this;
  89036. var controllerMesh = controller.webVRController.mesh;
  89037. if (controllerMesh) {
  89038. if (!controller._interactionsEnabled) {
  89039. this._enableInteractionOnController(controller);
  89040. }
  89041. controller._interactionsEnabled = true;
  89042. controller._teleportationEnabled = true;
  89043. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89044. controller._dpadPressed = false;
  89045. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  89046. controller._dpadPressed = stateObject.pressed;
  89047. if (!controller._dpadPressed) {
  89048. controller._rotationLeftAsked = false;
  89049. controller._rotationRightAsked = false;
  89050. controller._teleportationBackRequestInitiated = false;
  89051. }
  89052. });
  89053. }
  89054. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  89055. if (_this.teleportationEnabled) {
  89056. _this._checkTeleportBackwards(stateObject, controller);
  89057. _this._checkTeleportWithRay(stateObject, controller);
  89058. }
  89059. _this._checkRotate(stateObject, controller);
  89060. });
  89061. }
  89062. };
  89063. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  89064. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  89065. this._teleportationTarget.isPickable = false;
  89066. var length = 512;
  89067. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  89068. dynamicTexture.hasAlpha = true;
  89069. var context = dynamicTexture.getContext();
  89070. var centerX = length / 2;
  89071. var centerY = length / 2;
  89072. var radius = 200;
  89073. context.beginPath();
  89074. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  89075. context.fillStyle = this._teleportationFillColor;
  89076. context.fill();
  89077. context.lineWidth = 10;
  89078. context.strokeStyle = this._teleportationBorderColor;
  89079. context.stroke();
  89080. context.closePath();
  89081. dynamicTexture.update();
  89082. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  89083. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  89084. this._teleportationTarget.material = teleportationCircleMaterial;
  89085. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  89086. torus.isPickable = false;
  89087. torus.parent = this._teleportationTarget;
  89088. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  89089. var keys = [];
  89090. keys.push({
  89091. frame: 0,
  89092. value: 0
  89093. });
  89094. keys.push({
  89095. frame: 30,
  89096. value: 0.4
  89097. });
  89098. keys.push({
  89099. frame: 60,
  89100. value: 0
  89101. });
  89102. animationInnerCircle.setKeys(keys);
  89103. var easingFunction = new BABYLON.SineEase();
  89104. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  89105. animationInnerCircle.setEasingFunction(easingFunction);
  89106. torus.animations = [];
  89107. torus.animations.push(animationInnerCircle);
  89108. this._scene.beginAnimation(torus, 0, 60, true);
  89109. this._hideTeleportationTarget();
  89110. };
  89111. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  89112. this._teleportActive = true;
  89113. if (this._teleportationInitialized) {
  89114. this._teleportationTarget.isVisible = true;
  89115. if (this._isDefaultTeleportationTarget) {
  89116. this._teleportationTarget.getChildren()[0].isVisible = true;
  89117. }
  89118. }
  89119. };
  89120. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  89121. this._teleportActive = false;
  89122. if (this._teleportationInitialized) {
  89123. this._teleportationTarget.isVisible = false;
  89124. if (this._isDefaultTeleportationTarget) {
  89125. this._teleportationTarget.getChildren()[0].isVisible = false;
  89126. }
  89127. }
  89128. };
  89129. VRExperienceHelper.prototype._rotateCamera = function (right) {
  89130. var _this = this;
  89131. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89132. return;
  89133. }
  89134. if (right) {
  89135. this._rotationAngle++;
  89136. }
  89137. else {
  89138. this._rotationAngle--;
  89139. }
  89140. this.currentVRCamera.animations = [];
  89141. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  89142. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89143. var animationRotationKeys = [];
  89144. animationRotationKeys.push({
  89145. frame: 0,
  89146. value: this.currentVRCamera.rotationQuaternion
  89147. });
  89148. animationRotationKeys.push({
  89149. frame: 6,
  89150. value: target
  89151. });
  89152. animationRotation.setKeys(animationRotationKeys);
  89153. animationRotation.setEasingFunction(this._circleEase);
  89154. this.currentVRCamera.animations.push(animationRotation);
  89155. this._postProcessMove.animations = [];
  89156. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89157. var vignetteWeightKeys = [];
  89158. vignetteWeightKeys.push({
  89159. frame: 0,
  89160. value: 0
  89161. });
  89162. vignetteWeightKeys.push({
  89163. frame: 3,
  89164. value: 4
  89165. });
  89166. vignetteWeightKeys.push({
  89167. frame: 6,
  89168. value: 0
  89169. });
  89170. animationPP.setKeys(vignetteWeightKeys);
  89171. animationPP.setEasingFunction(this._circleEase);
  89172. this._postProcessMove.animations.push(animationPP);
  89173. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89174. var vignetteStretchKeys = [];
  89175. vignetteStretchKeys.push({
  89176. frame: 0,
  89177. value: 0
  89178. });
  89179. vignetteStretchKeys.push({
  89180. frame: 3,
  89181. value: 10
  89182. });
  89183. vignetteStretchKeys.push({
  89184. frame: 6,
  89185. value: 0
  89186. });
  89187. animationPP2.setKeys(vignetteStretchKeys);
  89188. animationPP2.setEasingFunction(this._circleEase);
  89189. this._postProcessMove.animations.push(animationPP2);
  89190. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89191. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89192. this._postProcessMove.samples = 4;
  89193. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89194. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  89195. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89196. });
  89197. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  89198. };
  89199. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  89200. if (hit.pickedPoint) {
  89201. if (gazer._teleportationRequestInitiated) {
  89202. this._displayTeleportationTarget();
  89203. this._haloCenter.copyFrom(hit.pickedPoint);
  89204. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  89205. }
  89206. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  89207. if (pickNormal) {
  89208. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89209. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89210. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  89211. }
  89212. this._teleportationTarget.position.y += 0.1;
  89213. }
  89214. };
  89215. VRExperienceHelper.prototype._teleportCamera = function (location) {
  89216. var _this = this;
  89217. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89218. return;
  89219. }
  89220. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  89221. // offset of the headset from the anchor.
  89222. if (this.webVRCamera.leftCamera) {
  89223. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  89224. this._workingVector.subtractInPlace(this.webVRCamera.position);
  89225. location.subtractToRef(this._workingVector, this._workingVector);
  89226. }
  89227. else {
  89228. this._workingVector.copyFrom(location);
  89229. }
  89230. // Add height to account for user's height offset
  89231. if (this.isInVRMode) {
  89232. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  89233. }
  89234. else {
  89235. this._workingVector.y += this._defaultHeight;
  89236. }
  89237. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  89238. // Create animation from the camera's position to the new location
  89239. this.currentVRCamera.animations = [];
  89240. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89241. var animationCameraTeleportationKeys = [{
  89242. frame: 0,
  89243. value: this.currentVRCamera.position
  89244. },
  89245. {
  89246. frame: 11,
  89247. value: this._workingVector
  89248. }
  89249. ];
  89250. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  89251. animationCameraTeleportation.setEasingFunction(this._circleEase);
  89252. this.currentVRCamera.animations.push(animationCameraTeleportation);
  89253. this._postProcessMove.animations = [];
  89254. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89255. var vignetteWeightKeys = [];
  89256. vignetteWeightKeys.push({
  89257. frame: 0,
  89258. value: 0
  89259. });
  89260. vignetteWeightKeys.push({
  89261. frame: 5,
  89262. value: 8
  89263. });
  89264. vignetteWeightKeys.push({
  89265. frame: 11,
  89266. value: 0
  89267. });
  89268. animationPP.setKeys(vignetteWeightKeys);
  89269. this._postProcessMove.animations.push(animationPP);
  89270. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89271. var vignetteStretchKeys = [];
  89272. vignetteStretchKeys.push({
  89273. frame: 0,
  89274. value: 0
  89275. });
  89276. vignetteStretchKeys.push({
  89277. frame: 5,
  89278. value: 10
  89279. });
  89280. vignetteStretchKeys.push({
  89281. frame: 11,
  89282. value: 0
  89283. });
  89284. animationPP2.setKeys(vignetteStretchKeys);
  89285. this._postProcessMove.animations.push(animationPP2);
  89286. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89287. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89288. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89289. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  89290. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89291. });
  89292. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  89293. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  89294. });
  89295. this._hideTeleportationTarget();
  89296. };
  89297. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  89298. if (normal) {
  89299. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  89300. if (angle < Math.PI / 2) {
  89301. normal.scaleInPlace(-1);
  89302. }
  89303. }
  89304. return normal;
  89305. };
  89306. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  89307. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89308. return;
  89309. }
  89310. var ray = gazer._getForwardRay(this._rayLength);
  89311. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89312. // Moving the gazeTracker on the mesh face targetted
  89313. if (hit && hit.pickedPoint) {
  89314. if (this._displayGaze) {
  89315. var multiplier = 1;
  89316. gazer._gazeTracker.isVisible = true;
  89317. if (gazer._isActionableMesh) {
  89318. multiplier = 3;
  89319. }
  89320. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  89321. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  89322. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  89323. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  89324. // To avoid z-fighting
  89325. var deltaFighting = 0.002;
  89326. if (pickNormal) {
  89327. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89328. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89329. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  89330. }
  89331. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  89332. if (gazer._gazeTracker.position.x < 0) {
  89333. gazer._gazeTracker.position.x += deltaFighting;
  89334. }
  89335. else {
  89336. gazer._gazeTracker.position.x -= deltaFighting;
  89337. }
  89338. if (gazer._gazeTracker.position.y < 0) {
  89339. gazer._gazeTracker.position.y += deltaFighting;
  89340. }
  89341. else {
  89342. gazer._gazeTracker.position.y -= deltaFighting;
  89343. }
  89344. if (gazer._gazeTracker.position.z < 0) {
  89345. gazer._gazeTracker.position.z += deltaFighting;
  89346. }
  89347. else {
  89348. gazer._gazeTracker.position.z -= deltaFighting;
  89349. }
  89350. }
  89351. // Changing the size of the laser pointer based on the distance from the targetted point
  89352. gazer._updatePointerDistance(hit.distance);
  89353. }
  89354. else {
  89355. gazer._updatePointerDistance();
  89356. gazer._gazeTracker.isVisible = false;
  89357. }
  89358. if (hit && hit.pickedMesh) {
  89359. gazer._currentHit = hit;
  89360. if (gazer._pointerDownOnMeshAsked) {
  89361. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  89362. }
  89363. // The object selected is the floor, we're in a teleportation scenario
  89364. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  89365. // Moving the teleportation area to this targetted point
  89366. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  89367. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  89368. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89369. }
  89370. gazer._currentMeshSelected = null;
  89371. if (gazer._teleportationRequestInitiated) {
  89372. this._moveTeleportationSelectorTo(hit, gazer, ray);
  89373. }
  89374. return;
  89375. }
  89376. // If not, we're in a selection scenario
  89377. //this._teleportationAllowed = false;
  89378. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  89379. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  89380. this.onNewMeshPicked.notifyObservers(hit);
  89381. gazer._currentMeshSelected = hit.pickedMesh;
  89382. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  89383. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  89384. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  89385. gazer._isActionableMesh = true;
  89386. }
  89387. else {
  89388. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89389. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89390. gazer._isActionableMesh = false;
  89391. }
  89392. try {
  89393. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  89394. }
  89395. catch (err) {
  89396. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  89397. }
  89398. }
  89399. else {
  89400. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89401. gazer._currentMeshSelected = null;
  89402. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89403. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89404. }
  89405. }
  89406. }
  89407. else {
  89408. gazer._currentHit = null;
  89409. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89410. gazer._currentMeshSelected = null;
  89411. //this._teleportationAllowed = false;
  89412. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89413. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89414. }
  89415. };
  89416. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  89417. if (mesh) {
  89418. this.onSelectedMeshUnselected.notifyObservers(mesh);
  89419. }
  89420. };
  89421. /**
  89422. * Sets the color of the laser ray from the vr controllers.
  89423. * @param color new color for the ray.
  89424. */
  89425. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  89426. if (this.leftController) {
  89427. this.leftController._setLaserPointerColor(color);
  89428. }
  89429. if (this.rightController) {
  89430. this.rightController._setLaserPointerColor(color);
  89431. }
  89432. };
  89433. /**
  89434. * Sets the color of the ray from the vr headsets gaze.
  89435. * @param color new color for the ray.
  89436. */
  89437. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  89438. if (!this._cameraGazer._gazeTracker.material) {
  89439. return;
  89440. }
  89441. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  89442. if (this.leftController) {
  89443. this.leftController._gazeTracker.material.emissiveColor = color;
  89444. }
  89445. if (this.rightController) {
  89446. this.rightController._gazeTracker.material.emissiveColor = color;
  89447. }
  89448. };
  89449. /**
  89450. * Exits VR and disposes of the vr experience helper
  89451. */
  89452. VRExperienceHelper.prototype.dispose = function () {
  89453. if (this.isInVRMode) {
  89454. this.exitVR();
  89455. }
  89456. if (this._postProcessMove) {
  89457. this._postProcessMove.dispose();
  89458. }
  89459. if (this._webVRCamera) {
  89460. this._webVRCamera.dispose();
  89461. }
  89462. if (this._vrDeviceOrientationCamera) {
  89463. this._vrDeviceOrientationCamera.dispose();
  89464. }
  89465. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  89466. document.body.removeChild(this._btnVR);
  89467. }
  89468. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  89469. this._deviceOrientationCamera.dispose();
  89470. }
  89471. if (this._cameraGazer) {
  89472. this._cameraGazer.dispose();
  89473. }
  89474. if (this.leftController) {
  89475. this.leftController.dispose();
  89476. }
  89477. if (this.rightController) {
  89478. this.rightController.dispose();
  89479. }
  89480. if (this._teleportationTarget) {
  89481. this._teleportationTarget.dispose();
  89482. }
  89483. this._floorMeshesCollection = [];
  89484. document.removeEventListener("keydown", this._onKeyDown);
  89485. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89486. window.removeEventListener("resize", this._onResize);
  89487. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  89488. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  89489. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  89490. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  89491. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  89492. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  89493. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  89494. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89495. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  89496. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  89497. this._scene.unregisterBeforeRender(this.beforeRender);
  89498. };
  89499. /**
  89500. * Gets the name of the VRExperienceHelper class
  89501. * @returns "VRExperienceHelper"
  89502. */
  89503. VRExperienceHelper.prototype.getClassName = function () {
  89504. return "VRExperienceHelper";
  89505. };
  89506. return VRExperienceHelper;
  89507. }());
  89508. BABYLON.VRExperienceHelper = VRExperienceHelper;
  89509. })(BABYLON || (BABYLON = {}));
  89510. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  89511. // Mainly based on these 2 articles :
  89512. // 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
  89513. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  89514. var BABYLON;
  89515. (function (BABYLON) {
  89516. /**
  89517. * Defines the potential axis of a Joystick
  89518. */
  89519. var JoystickAxis;
  89520. (function (JoystickAxis) {
  89521. /** X axis */
  89522. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  89523. /** Y axis */
  89524. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  89525. /** Z axis */
  89526. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  89527. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  89528. /**
  89529. * Class used to define virtual joystick (used in touch mode)
  89530. */
  89531. var VirtualJoystick = /** @class */ (function () {
  89532. /**
  89533. * Creates a new virtual joystick
  89534. * @param leftJoystick defines that the joystick is for left hand (false by default)
  89535. */
  89536. function VirtualJoystick(leftJoystick) {
  89537. var _this = this;
  89538. if (leftJoystick) {
  89539. this._leftJoystick = true;
  89540. }
  89541. else {
  89542. this._leftJoystick = false;
  89543. }
  89544. VirtualJoystick._globalJoystickIndex++;
  89545. // By default left & right arrow keys are moving the X
  89546. // and up & down keys are moving the Y
  89547. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89548. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89549. this.reverseLeftRight = false;
  89550. this.reverseUpDown = false;
  89551. // collections of pointers
  89552. this._touches = new BABYLON.StringDictionary();
  89553. this.deltaPosition = BABYLON.Vector3.Zero();
  89554. this._joystickSensibility = 25;
  89555. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89556. this._onResize = function (evt) {
  89557. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89558. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89559. if (VirtualJoystick.vjCanvas) {
  89560. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  89561. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  89562. }
  89563. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  89564. };
  89565. // injecting a canvas element on top of the canvas 3D game
  89566. if (!VirtualJoystick.vjCanvas) {
  89567. window.addEventListener("resize", this._onResize, false);
  89568. VirtualJoystick.vjCanvas = document.createElement("canvas");
  89569. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89570. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89571. VirtualJoystick.vjCanvas.width = window.innerWidth;
  89572. VirtualJoystick.vjCanvas.height = window.innerHeight;
  89573. VirtualJoystick.vjCanvas.style.width = "100%";
  89574. VirtualJoystick.vjCanvas.style.height = "100%";
  89575. VirtualJoystick.vjCanvas.style.position = "absolute";
  89576. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  89577. VirtualJoystick.vjCanvas.style.top = "0px";
  89578. VirtualJoystick.vjCanvas.style.left = "0px";
  89579. VirtualJoystick.vjCanvas.style.zIndex = "5";
  89580. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89581. // Support for jQuery PEP polyfill
  89582. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89583. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89584. if (!context) {
  89585. throw new Error("Unable to create canvas for virtual joystick");
  89586. }
  89587. VirtualJoystick.vjCanvasContext = context;
  89588. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89589. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89590. document.body.appendChild(VirtualJoystick.vjCanvas);
  89591. }
  89592. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89593. this.pressed = false;
  89594. // default joystick color
  89595. this._joystickColor = "cyan";
  89596. this._joystickPointerID = -1;
  89597. // current joystick position
  89598. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89599. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89600. // origin joystick position
  89601. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89602. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89603. this._onPointerDownHandlerRef = function (evt) {
  89604. _this._onPointerDown(evt);
  89605. };
  89606. this._onPointerMoveHandlerRef = function (evt) {
  89607. _this._onPointerMove(evt);
  89608. };
  89609. this._onPointerUpHandlerRef = function (evt) {
  89610. _this._onPointerUp(evt);
  89611. };
  89612. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89613. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89614. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89615. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89616. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89617. evt.preventDefault(); // Disables system menu
  89618. }, false);
  89619. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89620. }
  89621. /**
  89622. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89623. * @param newJoystickSensibility defines the new sensibility
  89624. */
  89625. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89626. this._joystickSensibility = newJoystickSensibility;
  89627. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89628. };
  89629. VirtualJoystick.prototype._onPointerDown = function (e) {
  89630. var positionOnScreenCondition;
  89631. e.preventDefault();
  89632. if (this._leftJoystick === true) {
  89633. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89634. }
  89635. else {
  89636. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89637. }
  89638. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89639. // First contact will be dedicated to the virtual joystick
  89640. this._joystickPointerID = e.pointerId;
  89641. this._joystickPointerStartPos.x = e.clientX;
  89642. this._joystickPointerStartPos.y = e.clientY;
  89643. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89644. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89645. this._deltaJoystickVector.x = 0;
  89646. this._deltaJoystickVector.y = 0;
  89647. this.pressed = true;
  89648. this._touches.add(e.pointerId.toString(), e);
  89649. }
  89650. else {
  89651. // You can only trigger the action buttons with a joystick declared
  89652. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89653. this._action();
  89654. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89655. }
  89656. }
  89657. };
  89658. VirtualJoystick.prototype._onPointerMove = function (e) {
  89659. // If the current pointer is the one associated to the joystick (first touch contact)
  89660. if (this._joystickPointerID == e.pointerId) {
  89661. this._joystickPointerPos.x = e.clientX;
  89662. this._joystickPointerPos.y = e.clientY;
  89663. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89664. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89665. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89666. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89667. switch (this._axisTargetedByLeftAndRight) {
  89668. case JoystickAxis.X:
  89669. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89670. break;
  89671. case JoystickAxis.Y:
  89672. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89673. break;
  89674. case JoystickAxis.Z:
  89675. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89676. break;
  89677. }
  89678. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89679. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89680. switch (this._axisTargetedByUpAndDown) {
  89681. case JoystickAxis.X:
  89682. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89683. break;
  89684. case JoystickAxis.Y:
  89685. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89686. break;
  89687. case JoystickAxis.Z:
  89688. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89689. break;
  89690. }
  89691. }
  89692. else {
  89693. var data = this._touches.get(e.pointerId.toString());
  89694. if (data) {
  89695. data.x = e.clientX;
  89696. data.y = e.clientY;
  89697. }
  89698. }
  89699. };
  89700. VirtualJoystick.prototype._onPointerUp = function (e) {
  89701. if (this._joystickPointerID == e.pointerId) {
  89702. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89703. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89704. this._joystickPointerID = -1;
  89705. this.pressed = false;
  89706. }
  89707. else {
  89708. var touch = this._touches.get(e.pointerId.toString());
  89709. if (touch) {
  89710. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89711. }
  89712. }
  89713. this._deltaJoystickVector.x = 0;
  89714. this._deltaJoystickVector.y = 0;
  89715. this._touches.remove(e.pointerId.toString());
  89716. };
  89717. /**
  89718. * Change the color of the virtual joystick
  89719. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89720. */
  89721. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89722. this._joystickColor = newColor;
  89723. };
  89724. /**
  89725. * Defines a callback to call when the joystick is touched
  89726. * @param action defines the callback
  89727. */
  89728. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89729. this._action = action;
  89730. };
  89731. /**
  89732. * Defines which axis you'd like to control for left & right
  89733. * @param axis defines the axis to use
  89734. */
  89735. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89736. switch (axis) {
  89737. case JoystickAxis.X:
  89738. case JoystickAxis.Y:
  89739. case JoystickAxis.Z:
  89740. this._axisTargetedByLeftAndRight = axis;
  89741. break;
  89742. default:
  89743. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89744. break;
  89745. }
  89746. };
  89747. /**
  89748. * Defines which axis you'd like to control for up & down
  89749. * @param axis defines the axis to use
  89750. */
  89751. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89752. switch (axis) {
  89753. case JoystickAxis.X:
  89754. case JoystickAxis.Y:
  89755. case JoystickAxis.Z:
  89756. this._axisTargetedByUpAndDown = axis;
  89757. break;
  89758. default:
  89759. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89760. break;
  89761. }
  89762. };
  89763. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89764. var _this = this;
  89765. if (this.pressed) {
  89766. this._touches.forEach(function (key, touch) {
  89767. if (touch.pointerId === _this._joystickPointerID) {
  89768. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89769. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89770. VirtualJoystick.vjCanvasContext.beginPath();
  89771. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89772. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89773. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89774. VirtualJoystick.vjCanvasContext.stroke();
  89775. VirtualJoystick.vjCanvasContext.closePath();
  89776. VirtualJoystick.vjCanvasContext.beginPath();
  89777. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89778. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89779. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89780. VirtualJoystick.vjCanvasContext.stroke();
  89781. VirtualJoystick.vjCanvasContext.closePath();
  89782. VirtualJoystick.vjCanvasContext.beginPath();
  89783. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89784. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89785. VirtualJoystick.vjCanvasContext.stroke();
  89786. VirtualJoystick.vjCanvasContext.closePath();
  89787. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89788. }
  89789. else {
  89790. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89791. VirtualJoystick.vjCanvasContext.beginPath();
  89792. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89793. VirtualJoystick.vjCanvasContext.beginPath();
  89794. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89795. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89796. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89797. VirtualJoystick.vjCanvasContext.stroke();
  89798. VirtualJoystick.vjCanvasContext.closePath();
  89799. touch.prevX = touch.x;
  89800. touch.prevY = touch.y;
  89801. }
  89802. ;
  89803. });
  89804. }
  89805. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89806. };
  89807. /**
  89808. * Release internal HTML canvas
  89809. */
  89810. VirtualJoystick.prototype.releaseCanvas = function () {
  89811. if (VirtualJoystick.vjCanvas) {
  89812. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89813. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89814. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89815. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89816. window.removeEventListener("resize", this._onResize);
  89817. document.body.removeChild(VirtualJoystick.vjCanvas);
  89818. VirtualJoystick.vjCanvas = null;
  89819. }
  89820. };
  89821. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89822. VirtualJoystick._globalJoystickIndex = 0;
  89823. return VirtualJoystick;
  89824. }());
  89825. BABYLON.VirtualJoystick = VirtualJoystick;
  89826. })(BABYLON || (BABYLON = {}));
  89827. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89828. var BABYLON;
  89829. (function (BABYLON) {
  89830. // We're mainly based on the logic defined into the FreeCamera code
  89831. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89832. __extends(VirtualJoysticksCamera, _super);
  89833. function VirtualJoysticksCamera(name, position, scene) {
  89834. var _this = _super.call(this, name, position, scene) || this;
  89835. _this.inputs.addVirtualJoystick();
  89836. return _this;
  89837. }
  89838. VirtualJoysticksCamera.prototype.getClassName = function () {
  89839. return "VirtualJoysticksCamera";
  89840. };
  89841. return VirtualJoysticksCamera;
  89842. }(BABYLON.FreeCamera));
  89843. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89844. })(BABYLON || (BABYLON = {}));
  89845. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89846. var BABYLON;
  89847. (function (BABYLON) {
  89848. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89849. function FreeCameraVirtualJoystickInput() {
  89850. }
  89851. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89852. return this._leftjoystick;
  89853. };
  89854. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89855. return this._rightjoystick;
  89856. };
  89857. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89858. if (this._leftjoystick) {
  89859. var camera = this.camera;
  89860. var speed = camera._computeLocalCameraSpeed() * 50;
  89861. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89862. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89863. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89864. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89865. if (!this._leftjoystick.pressed) {
  89866. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89867. }
  89868. if (!this._rightjoystick.pressed) {
  89869. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89870. }
  89871. }
  89872. };
  89873. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89874. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89875. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89876. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89877. this._leftjoystick.setJoystickSensibility(0.15);
  89878. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89879. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89880. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89881. this._rightjoystick.reverseUpDown = true;
  89882. this._rightjoystick.setJoystickSensibility(0.05);
  89883. this._rightjoystick.setJoystickColor("yellow");
  89884. };
  89885. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89886. this._leftjoystick.releaseCanvas();
  89887. this._rightjoystick.releaseCanvas();
  89888. };
  89889. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89890. return "FreeCameraVirtualJoystickInput";
  89891. };
  89892. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89893. return "virtualJoystick";
  89894. };
  89895. return FreeCameraVirtualJoystickInput;
  89896. }());
  89897. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89898. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89899. })(BABYLON || (BABYLON = {}));
  89900. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89901. var BABYLON;
  89902. (function (BABYLON) {
  89903. var SimplificationSettings = /** @class */ (function () {
  89904. function SimplificationSettings(quality, distance, optimizeMesh) {
  89905. this.quality = quality;
  89906. this.distance = distance;
  89907. this.optimizeMesh = optimizeMesh;
  89908. }
  89909. return SimplificationSettings;
  89910. }());
  89911. BABYLON.SimplificationSettings = SimplificationSettings;
  89912. var SimplificationQueue = /** @class */ (function () {
  89913. function SimplificationQueue() {
  89914. this.running = false;
  89915. this._simplificationArray = [];
  89916. }
  89917. SimplificationQueue.prototype.addTask = function (task) {
  89918. this._simplificationArray.push(task);
  89919. };
  89920. SimplificationQueue.prototype.executeNext = function () {
  89921. var task = this._simplificationArray.pop();
  89922. if (task) {
  89923. this.running = true;
  89924. this.runSimplification(task);
  89925. }
  89926. else {
  89927. this.running = false;
  89928. }
  89929. };
  89930. SimplificationQueue.prototype.runSimplification = function (task) {
  89931. var _this = this;
  89932. if (task.parallelProcessing) {
  89933. //parallel simplifier
  89934. task.settings.forEach(function (setting) {
  89935. var simplifier = _this.getSimplifier(task);
  89936. simplifier.simplify(setting, function (newMesh) {
  89937. task.mesh.addLODLevel(setting.distance, newMesh);
  89938. newMesh.isVisible = true;
  89939. //check if it is the last
  89940. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89941. //all done, run the success callback.
  89942. task.successCallback();
  89943. }
  89944. _this.executeNext();
  89945. });
  89946. });
  89947. }
  89948. else {
  89949. //single simplifier.
  89950. var simplifier = this.getSimplifier(task);
  89951. var runDecimation = function (setting, callback) {
  89952. simplifier.simplify(setting, function (newMesh) {
  89953. task.mesh.addLODLevel(setting.distance, newMesh);
  89954. newMesh.isVisible = true;
  89955. //run the next quality level
  89956. callback();
  89957. });
  89958. };
  89959. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89960. runDecimation(task.settings[loop.index], function () {
  89961. loop.executeNext();
  89962. });
  89963. }, function () {
  89964. //execution ended, run the success callback.
  89965. if (task.successCallback) {
  89966. task.successCallback();
  89967. }
  89968. _this.executeNext();
  89969. });
  89970. }
  89971. };
  89972. SimplificationQueue.prototype.getSimplifier = function (task) {
  89973. switch (task.simplificationType) {
  89974. case SimplificationType.QUADRATIC:
  89975. default:
  89976. return new QuadraticErrorSimplification(task.mesh);
  89977. }
  89978. };
  89979. return SimplificationQueue;
  89980. }());
  89981. BABYLON.SimplificationQueue = SimplificationQueue;
  89982. /**
  89983. * The implemented types of simplification
  89984. * At the moment only Quadratic Error Decimation is implemented
  89985. */
  89986. var SimplificationType;
  89987. (function (SimplificationType) {
  89988. /** Quadratic error decimation */
  89989. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89990. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89991. var DecimationTriangle = /** @class */ (function () {
  89992. function DecimationTriangle(vertices) {
  89993. this.vertices = vertices;
  89994. this.error = new Array(4);
  89995. this.deleted = false;
  89996. this.isDirty = false;
  89997. this.deletePending = false;
  89998. this.borderFactor = 0;
  89999. }
  90000. return DecimationTriangle;
  90001. }());
  90002. BABYLON.DecimationTriangle = DecimationTriangle;
  90003. var DecimationVertex = /** @class */ (function () {
  90004. function DecimationVertex(position, id) {
  90005. this.position = position;
  90006. this.id = id;
  90007. this.isBorder = true;
  90008. this.q = new QuadraticMatrix();
  90009. this.triangleCount = 0;
  90010. this.triangleStart = 0;
  90011. this.originalOffsets = [];
  90012. }
  90013. DecimationVertex.prototype.updatePosition = function (newPosition) {
  90014. this.position.copyFrom(newPosition);
  90015. };
  90016. return DecimationVertex;
  90017. }());
  90018. BABYLON.DecimationVertex = DecimationVertex;
  90019. var QuadraticMatrix = /** @class */ (function () {
  90020. function QuadraticMatrix(data) {
  90021. this.data = new Array(10);
  90022. for (var i = 0; i < 10; ++i) {
  90023. if (data && data[i]) {
  90024. this.data[i] = data[i];
  90025. }
  90026. else {
  90027. this.data[i] = 0;
  90028. }
  90029. }
  90030. }
  90031. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  90032. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  90033. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  90034. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  90035. return det;
  90036. };
  90037. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  90038. for (var i = 0; i < 10; ++i) {
  90039. this.data[i] += matrix.data[i];
  90040. }
  90041. };
  90042. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  90043. for (var i = 0; i < 10; ++i) {
  90044. this.data[i] += data[i];
  90045. }
  90046. };
  90047. QuadraticMatrix.prototype.add = function (matrix) {
  90048. var m = new QuadraticMatrix();
  90049. for (var i = 0; i < 10; ++i) {
  90050. m.data[i] = this.data[i] + matrix.data[i];
  90051. }
  90052. return m;
  90053. };
  90054. QuadraticMatrix.FromData = function (a, b, c, d) {
  90055. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  90056. };
  90057. //returning an array to avoid garbage collection
  90058. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  90059. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  90060. };
  90061. return QuadraticMatrix;
  90062. }());
  90063. BABYLON.QuadraticMatrix = QuadraticMatrix;
  90064. var Reference = /** @class */ (function () {
  90065. function Reference(vertexId, triangleId) {
  90066. this.vertexId = vertexId;
  90067. this.triangleId = triangleId;
  90068. }
  90069. return Reference;
  90070. }());
  90071. BABYLON.Reference = Reference;
  90072. /**
  90073. * An implementation of the Quadratic Error simplification algorithm.
  90074. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  90075. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  90076. * @author RaananW
  90077. */
  90078. var QuadraticErrorSimplification = /** @class */ (function () {
  90079. function QuadraticErrorSimplification(_mesh) {
  90080. this._mesh = _mesh;
  90081. this.syncIterations = 5000;
  90082. this.aggressiveness = 7;
  90083. this.decimationIterations = 100;
  90084. this.boundingBoxEpsilon = BABYLON.Epsilon;
  90085. }
  90086. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  90087. var _this = this;
  90088. this.initDecimatedMesh();
  90089. //iterating through the submeshes array, one after the other.
  90090. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  90091. _this.initWithMesh(loop.index, function () {
  90092. _this.runDecimation(settings, loop.index, function () {
  90093. loop.executeNext();
  90094. });
  90095. }, settings.optimizeMesh);
  90096. }, function () {
  90097. setTimeout(function () {
  90098. successCallback(_this._reconstructedMesh);
  90099. }, 0);
  90100. });
  90101. };
  90102. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  90103. var _this = this;
  90104. var targetCount = ~~(this.triangles.length * settings.quality);
  90105. var deletedTriangles = 0;
  90106. var triangleCount = this.triangles.length;
  90107. var iterationFunction = function (iteration, callback) {
  90108. setTimeout(function () {
  90109. if (iteration % 5 === 0) {
  90110. _this.updateMesh(iteration === 0);
  90111. }
  90112. for (var i = 0; i < _this.triangles.length; ++i) {
  90113. _this.triangles[i].isDirty = false;
  90114. }
  90115. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  90116. var trianglesIterator = function (i) {
  90117. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  90118. var t = _this.triangles[tIdx];
  90119. if (!t)
  90120. return;
  90121. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  90122. return;
  90123. }
  90124. for (var j = 0; j < 3; ++j) {
  90125. if (t.error[j] < threshold) {
  90126. var deleted0 = [];
  90127. var deleted1 = [];
  90128. var v0 = t.vertices[j];
  90129. var v1 = t.vertices[(j + 1) % 3];
  90130. if (v0.isBorder || v1.isBorder)
  90131. continue;
  90132. var p = BABYLON.Vector3.Zero();
  90133. var n = BABYLON.Vector3.Zero();
  90134. var uv = BABYLON.Vector2.Zero();
  90135. var color = new BABYLON.Color4(0, 0, 0, 1);
  90136. _this.calculateError(v0, v1, p, n, uv, color);
  90137. var delTr = new Array();
  90138. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  90139. continue;
  90140. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  90141. continue;
  90142. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  90143. continue;
  90144. var uniqueArray = new Array();
  90145. delTr.forEach(function (deletedT) {
  90146. if (uniqueArray.indexOf(deletedT) === -1) {
  90147. deletedT.deletePending = true;
  90148. uniqueArray.push(deletedT);
  90149. }
  90150. });
  90151. if (uniqueArray.length % 2 !== 0) {
  90152. continue;
  90153. }
  90154. v0.q = v1.q.add(v0.q);
  90155. v0.updatePosition(p);
  90156. var tStart = _this.references.length;
  90157. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  90158. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  90159. var tCount = _this.references.length - tStart;
  90160. if (tCount <= v0.triangleCount) {
  90161. if (tCount) {
  90162. for (var c = 0; c < tCount; c++) {
  90163. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  90164. }
  90165. }
  90166. }
  90167. else {
  90168. v0.triangleStart = tStart;
  90169. }
  90170. v0.triangleCount = tCount;
  90171. break;
  90172. }
  90173. }
  90174. };
  90175. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  90176. }, 0);
  90177. };
  90178. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  90179. if (triangleCount - deletedTriangles <= targetCount)
  90180. loop.breakLoop();
  90181. else {
  90182. iterationFunction(loop.index, function () {
  90183. loop.executeNext();
  90184. });
  90185. }
  90186. }, function () {
  90187. setTimeout(function () {
  90188. //reconstruct this part of the mesh
  90189. _this.reconstructMesh(submeshIndex);
  90190. successCallback();
  90191. }, 0);
  90192. });
  90193. };
  90194. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  90195. var _this = this;
  90196. this.vertices = [];
  90197. this.triangles = [];
  90198. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90199. var indices = this._mesh.getIndices();
  90200. var submesh = this._mesh.subMeshes[submeshIndex];
  90201. var findInVertices = function (positionToSearch) {
  90202. if (optimizeMesh) {
  90203. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  90204. if (_this.vertices[ii].position.equals(positionToSearch)) {
  90205. return _this.vertices[ii];
  90206. }
  90207. }
  90208. }
  90209. return null;
  90210. };
  90211. var vertexReferences = [];
  90212. var vertexInit = function (i) {
  90213. if (!positionData) {
  90214. return;
  90215. }
  90216. var offset = i + submesh.verticesStart;
  90217. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  90218. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  90219. vertex.originalOffsets.push(offset);
  90220. if (vertex.id === _this.vertices.length) {
  90221. _this.vertices.push(vertex);
  90222. }
  90223. vertexReferences.push(vertex.id);
  90224. };
  90225. //var totalVertices = mesh.getTotalVertices();
  90226. var totalVertices = submesh.verticesCount;
  90227. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  90228. var indicesInit = function (i) {
  90229. if (!indices) {
  90230. return;
  90231. }
  90232. var offset = (submesh.indexStart / 3) + i;
  90233. var pos = (offset * 3);
  90234. var i0 = indices[pos + 0];
  90235. var i1 = indices[pos + 1];
  90236. var i2 = indices[pos + 2];
  90237. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  90238. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  90239. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  90240. var triangle = new DecimationTriangle([v0, v1, v2]);
  90241. triangle.originalOffset = pos;
  90242. _this.triangles.push(triangle);
  90243. };
  90244. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  90245. _this.init(callback);
  90246. });
  90247. });
  90248. };
  90249. QuadraticErrorSimplification.prototype.init = function (callback) {
  90250. var _this = this;
  90251. var triangleInit1 = function (i) {
  90252. var t = _this.triangles[i];
  90253. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  90254. for (var j = 0; j < 3; j++) {
  90255. 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))));
  90256. }
  90257. };
  90258. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  90259. var triangleInit2 = function (i) {
  90260. var t = _this.triangles[i];
  90261. for (var j = 0; j < 3; ++j) {
  90262. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  90263. }
  90264. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90265. };
  90266. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  90267. callback();
  90268. });
  90269. });
  90270. };
  90271. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  90272. var newTriangles = [];
  90273. var i;
  90274. for (i = 0; i < this.vertices.length; ++i) {
  90275. this.vertices[i].triangleCount = 0;
  90276. }
  90277. var t;
  90278. var j;
  90279. for (i = 0; i < this.triangles.length; ++i) {
  90280. if (!this.triangles[i].deleted) {
  90281. t = this.triangles[i];
  90282. for (j = 0; j < 3; ++j) {
  90283. t.vertices[j].triangleCount = 1;
  90284. }
  90285. newTriangles.push(t);
  90286. }
  90287. }
  90288. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  90289. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  90290. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  90291. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  90292. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  90293. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  90294. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  90295. var vertexCount = 0;
  90296. for (i = 0; i < this.vertices.length; ++i) {
  90297. var vertex = this.vertices[i];
  90298. vertex.id = vertexCount;
  90299. if (vertex.triangleCount) {
  90300. vertex.originalOffsets.forEach(function (originalOffset) {
  90301. if (!normalData) {
  90302. return;
  90303. }
  90304. newPositionData.push(vertex.position.x);
  90305. newPositionData.push(vertex.position.y);
  90306. newPositionData.push(vertex.position.z);
  90307. newNormalData.push(normalData[originalOffset * 3]);
  90308. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  90309. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  90310. if (uvs && uvs.length) {
  90311. newUVsData.push(uvs[(originalOffset * 2)]);
  90312. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  90313. }
  90314. else if (colorsData && colorsData.length) {
  90315. newColorsData.push(colorsData[(originalOffset * 4)]);
  90316. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  90317. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  90318. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  90319. }
  90320. ++vertexCount;
  90321. });
  90322. }
  90323. }
  90324. var startingIndex = this._reconstructedMesh.getTotalIndices();
  90325. var startingVertex = this._reconstructedMesh.getTotalVertices();
  90326. var submeshesArray = this._reconstructedMesh.subMeshes;
  90327. this._reconstructedMesh.subMeshes = [];
  90328. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  90329. var originalIndices = this._mesh.getIndices();
  90330. for (i = 0; i < newTriangles.length; ++i) {
  90331. t = newTriangles[i]; //now get the new referencing point for each vertex
  90332. [0, 1, 2].forEach(function (idx) {
  90333. var id = originalIndices[t.originalOffset + idx];
  90334. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  90335. if (offset < 0)
  90336. offset = 0;
  90337. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  90338. });
  90339. }
  90340. //overwriting the old vertex buffers and indices.
  90341. this._reconstructedMesh.setIndices(newIndicesArray);
  90342. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  90343. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  90344. if (newUVsData.length > 0)
  90345. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  90346. if (newColorsData.length > 0)
  90347. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  90348. //create submesh
  90349. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  90350. if (submeshIndex > 0) {
  90351. this._reconstructedMesh.subMeshes = [];
  90352. submeshesArray.forEach(function (submesh) {
  90353. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  90354. });
  90355. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  90356. }
  90357. };
  90358. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  90359. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  90360. this._reconstructedMesh.material = this._mesh.material;
  90361. this._reconstructedMesh.parent = this._mesh.parent;
  90362. this._reconstructedMesh.isVisible = false;
  90363. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  90364. };
  90365. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  90366. for (var i = 0; i < vertex1.triangleCount; ++i) {
  90367. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  90368. if (t.deleted)
  90369. continue;
  90370. var s = this.references[vertex1.triangleStart + i].vertexId;
  90371. var v1 = t.vertices[(s + 1) % 3];
  90372. var v2 = t.vertices[(s + 2) % 3];
  90373. if ((v1 === vertex2 || v2 === vertex2)) {
  90374. deletedArray[i] = true;
  90375. delTr.push(t);
  90376. continue;
  90377. }
  90378. var d1 = v1.position.subtract(point);
  90379. d1 = d1.normalize();
  90380. var d2 = v2.position.subtract(point);
  90381. d2 = d2.normalize();
  90382. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  90383. return true;
  90384. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  90385. deletedArray[i] = false;
  90386. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  90387. return true;
  90388. }
  90389. return false;
  90390. };
  90391. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  90392. var newDeleted = deletedTriangles;
  90393. for (var i = 0; i < vertex.triangleCount; ++i) {
  90394. var ref = this.references[vertex.triangleStart + i];
  90395. var t = this.triangles[ref.triangleId];
  90396. if (t.deleted)
  90397. continue;
  90398. if (deletedArray[i] && t.deletePending) {
  90399. t.deleted = true;
  90400. newDeleted++;
  90401. continue;
  90402. }
  90403. t.vertices[ref.vertexId] = origVertex;
  90404. t.isDirty = true;
  90405. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  90406. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  90407. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  90408. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90409. this.references.push(ref);
  90410. }
  90411. return newDeleted;
  90412. };
  90413. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  90414. for (var i = 0; i < this.vertices.length; ++i) {
  90415. var vCount = [];
  90416. var vId = [];
  90417. var v = this.vertices[i];
  90418. var j;
  90419. for (j = 0; j < v.triangleCount; ++j) {
  90420. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  90421. for (var ii = 0; ii < 3; ii++) {
  90422. var ofs = 0;
  90423. var vv = triangle.vertices[ii];
  90424. while (ofs < vCount.length) {
  90425. if (vId[ofs] === vv.id)
  90426. break;
  90427. ++ofs;
  90428. }
  90429. if (ofs === vCount.length) {
  90430. vCount.push(1);
  90431. vId.push(vv.id);
  90432. }
  90433. else {
  90434. vCount[ofs]++;
  90435. }
  90436. }
  90437. }
  90438. for (j = 0; j < vCount.length; ++j) {
  90439. if (vCount[j] === 1) {
  90440. this.vertices[vId[j]].isBorder = true;
  90441. }
  90442. else {
  90443. this.vertices[vId[j]].isBorder = false;
  90444. }
  90445. }
  90446. }
  90447. };
  90448. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  90449. if (identifyBorders === void 0) { identifyBorders = false; }
  90450. var i;
  90451. if (!identifyBorders) {
  90452. var newTrianglesVector = [];
  90453. for (i = 0; i < this.triangles.length; ++i) {
  90454. if (!this.triangles[i].deleted) {
  90455. newTrianglesVector.push(this.triangles[i]);
  90456. }
  90457. }
  90458. this.triangles = newTrianglesVector;
  90459. }
  90460. for (i = 0; i < this.vertices.length; ++i) {
  90461. this.vertices[i].triangleCount = 0;
  90462. this.vertices[i].triangleStart = 0;
  90463. }
  90464. var t;
  90465. var j;
  90466. var v;
  90467. for (i = 0; i < this.triangles.length; ++i) {
  90468. t = this.triangles[i];
  90469. for (j = 0; j < 3; ++j) {
  90470. v = t.vertices[j];
  90471. v.triangleCount++;
  90472. }
  90473. }
  90474. var tStart = 0;
  90475. for (i = 0; i < this.vertices.length; ++i) {
  90476. this.vertices[i].triangleStart = tStart;
  90477. tStart += this.vertices[i].triangleCount;
  90478. this.vertices[i].triangleCount = 0;
  90479. }
  90480. var newReferences = new Array(this.triangles.length * 3);
  90481. for (i = 0; i < this.triangles.length; ++i) {
  90482. t = this.triangles[i];
  90483. for (j = 0; j < 3; ++j) {
  90484. v = t.vertices[j];
  90485. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  90486. v.triangleCount++;
  90487. }
  90488. }
  90489. this.references = newReferences;
  90490. if (identifyBorders) {
  90491. this.identifyBorder();
  90492. }
  90493. };
  90494. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  90495. var x = point.x;
  90496. var y = point.y;
  90497. var z = point.z;
  90498. 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
  90499. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  90500. };
  90501. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  90502. var q = vertex1.q.add(vertex2.q);
  90503. var border = vertex1.isBorder && vertex2.isBorder;
  90504. var error = 0;
  90505. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  90506. if (qDet !== 0 && !border) {
  90507. if (!pointResult) {
  90508. pointResult = BABYLON.Vector3.Zero();
  90509. }
  90510. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  90511. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  90512. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  90513. error = this.vertexError(q, pointResult);
  90514. }
  90515. else {
  90516. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  90517. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  90518. var error1 = this.vertexError(q, vertex1.position);
  90519. var error2 = this.vertexError(q, vertex2.position);
  90520. var error3 = this.vertexError(q, p3);
  90521. error = Math.min(error1, error2, error3);
  90522. if (error === error1) {
  90523. if (pointResult) {
  90524. pointResult.copyFrom(vertex1.position);
  90525. }
  90526. }
  90527. else if (error === error2) {
  90528. if (pointResult) {
  90529. pointResult.copyFrom(vertex2.position);
  90530. }
  90531. }
  90532. else {
  90533. if (pointResult) {
  90534. pointResult.copyFrom(p3);
  90535. }
  90536. }
  90537. }
  90538. return error;
  90539. };
  90540. return QuadraticErrorSimplification;
  90541. }());
  90542. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  90543. })(BABYLON || (BABYLON = {}));
  90544. //# sourceMappingURL=babylon.meshSimplification.js.map
  90545. var BABYLON;
  90546. (function (BABYLON) {
  90547. var MeshLODLevel = /** @class */ (function () {
  90548. function MeshLODLevel(distance, mesh) {
  90549. this.distance = distance;
  90550. this.mesh = mesh;
  90551. }
  90552. return MeshLODLevel;
  90553. }());
  90554. BABYLON.MeshLODLevel = MeshLODLevel;
  90555. })(BABYLON || (BABYLON = {}));
  90556. //# sourceMappingURL=babylon.meshLODLevel.js.map
  90557. var BABYLON;
  90558. (function (BABYLON) {
  90559. /**
  90560. * Defines the root class used to create scene optimization to use with SceneOptimizer
  90561. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90562. */
  90563. var SceneOptimization = /** @class */ (function () {
  90564. /**
  90565. * Creates the SceneOptimization object
  90566. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90567. * @param desc defines the description associated with the optimization
  90568. */
  90569. function SceneOptimization(
  90570. /**
  90571. * Defines the priority of this optimization (0 by default which means first in the list)
  90572. */
  90573. priority) {
  90574. if (priority === void 0) { priority = 0; }
  90575. this.priority = priority;
  90576. }
  90577. /**
  90578. * Gets a string describing the action executed by the current optimization
  90579. * @returns description string
  90580. */
  90581. SceneOptimization.prototype.getDescription = function () {
  90582. return "";
  90583. };
  90584. /**
  90585. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90586. * @param scene defines the current scene where to apply this optimization
  90587. * @param optimizer defines the current optimizer
  90588. * @returns true if everything that can be done was applied
  90589. */
  90590. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90591. return true;
  90592. };
  90593. ;
  90594. return SceneOptimization;
  90595. }());
  90596. BABYLON.SceneOptimization = SceneOptimization;
  90597. /**
  90598. * Defines an optimization used to reduce the size of render target textures
  90599. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90600. */
  90601. var TextureOptimization = /** @class */ (function (_super) {
  90602. __extends(TextureOptimization, _super);
  90603. /**
  90604. * Creates the TextureOptimization object
  90605. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90606. * @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
  90607. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90608. */
  90609. function TextureOptimization(
  90610. /**
  90611. * Defines the priority of this optimization (0 by default which means first in the list)
  90612. */
  90613. priority,
  90614. /**
  90615. * 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
  90616. */
  90617. maximumSize,
  90618. /**
  90619. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90620. */
  90621. step) {
  90622. if (priority === void 0) { priority = 0; }
  90623. if (maximumSize === void 0) { maximumSize = 1024; }
  90624. if (step === void 0) { step = 0.5; }
  90625. var _this = _super.call(this, priority) || this;
  90626. _this.priority = priority;
  90627. _this.maximumSize = maximumSize;
  90628. _this.step = step;
  90629. return _this;
  90630. }
  90631. /**
  90632. * Gets a string describing the action executed by the current optimization
  90633. * @returns description string
  90634. */
  90635. TextureOptimization.prototype.getDescription = function () {
  90636. return "Reducing render target texture size to " + this.maximumSize;
  90637. };
  90638. /**
  90639. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90640. * @param scene defines the current scene where to apply this optimization
  90641. * @param optimizer defines the current optimizer
  90642. * @returns true if everything that can be done was applied
  90643. */
  90644. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90645. var allDone = true;
  90646. for (var index = 0; index < scene.textures.length; index++) {
  90647. var texture = scene.textures[index];
  90648. if (!texture.canRescale || texture.getContext) {
  90649. continue;
  90650. }
  90651. var currentSize = texture.getSize();
  90652. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90653. if (maxDimension > this.maximumSize) {
  90654. texture.scale(this.step);
  90655. allDone = false;
  90656. }
  90657. }
  90658. return allDone;
  90659. };
  90660. return TextureOptimization;
  90661. }(SceneOptimization));
  90662. BABYLON.TextureOptimization = TextureOptimization;
  90663. /**
  90664. * Defines an optimization used to increase or decrease the rendering resolution
  90665. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90666. */
  90667. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90668. __extends(HardwareScalingOptimization, _super);
  90669. /**
  90670. * Creates the HardwareScalingOptimization object
  90671. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90672. * @param maximumScale defines the maximum scale to use (2 by default)
  90673. * @param step defines the step to use between two passes (0.5 by default)
  90674. */
  90675. function HardwareScalingOptimization(
  90676. /**
  90677. * Defines the priority of this optimization (0 by default which means first in the list)
  90678. */
  90679. priority,
  90680. /**
  90681. * Defines the maximum scale to use (2 by default)
  90682. */
  90683. maximumScale,
  90684. /**
  90685. * Defines the step to use between two passes (0.5 by default)
  90686. */
  90687. step) {
  90688. if (priority === void 0) { priority = 0; }
  90689. if (maximumScale === void 0) { maximumScale = 2; }
  90690. if (step === void 0) { step = 0.25; }
  90691. var _this = _super.call(this, priority) || this;
  90692. _this.priority = priority;
  90693. _this.maximumScale = maximumScale;
  90694. _this.step = step;
  90695. _this._currentScale = -1;
  90696. _this._directionOffset = 1;
  90697. return _this;
  90698. }
  90699. /**
  90700. * Gets a string describing the action executed by the current optimization
  90701. * @return description string
  90702. */
  90703. HardwareScalingOptimization.prototype.getDescription = function () {
  90704. return "Setting hardware scaling level to " + this._currentScale;
  90705. };
  90706. /**
  90707. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90708. * @param scene defines the current scene where to apply this optimization
  90709. * @param optimizer defines the current optimizer
  90710. * @returns true if everything that can be done was applied
  90711. */
  90712. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90713. if (this._currentScale === -1) {
  90714. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90715. if (this._currentScale > this.maximumScale) {
  90716. this._directionOffset = -1;
  90717. }
  90718. }
  90719. this._currentScale += this._directionOffset * this.step;
  90720. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90721. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90722. };
  90723. ;
  90724. return HardwareScalingOptimization;
  90725. }(SceneOptimization));
  90726. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90727. /**
  90728. * Defines an optimization used to remove shadows
  90729. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90730. */
  90731. var ShadowsOptimization = /** @class */ (function (_super) {
  90732. __extends(ShadowsOptimization, _super);
  90733. function ShadowsOptimization() {
  90734. return _super !== null && _super.apply(this, arguments) || this;
  90735. }
  90736. /**
  90737. * Gets a string describing the action executed by the current optimization
  90738. * @return description string
  90739. */
  90740. ShadowsOptimization.prototype.getDescription = function () {
  90741. return "Turning shadows on/off";
  90742. };
  90743. /**
  90744. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90745. * @param scene defines the current scene where to apply this optimization
  90746. * @param optimizer defines the current optimizer
  90747. * @returns true if everything that can be done was applied
  90748. */
  90749. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90750. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90751. return true;
  90752. };
  90753. ;
  90754. return ShadowsOptimization;
  90755. }(SceneOptimization));
  90756. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90757. /**
  90758. * Defines an optimization used to turn post-processes off
  90759. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90760. */
  90761. var PostProcessesOptimization = /** @class */ (function (_super) {
  90762. __extends(PostProcessesOptimization, _super);
  90763. function PostProcessesOptimization() {
  90764. return _super !== null && _super.apply(this, arguments) || this;
  90765. }
  90766. /**
  90767. * Gets a string describing the action executed by the current optimization
  90768. * @return description string
  90769. */
  90770. PostProcessesOptimization.prototype.getDescription = function () {
  90771. return "Turning post-processes on/off";
  90772. };
  90773. /**
  90774. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90775. * @param scene defines the current scene where to apply this optimization
  90776. * @param optimizer defines the current optimizer
  90777. * @returns true if everything that can be done was applied
  90778. */
  90779. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90780. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90781. return true;
  90782. };
  90783. ;
  90784. return PostProcessesOptimization;
  90785. }(SceneOptimization));
  90786. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90787. /**
  90788. * Defines an optimization used to turn lens flares off
  90789. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90790. */
  90791. var LensFlaresOptimization = /** @class */ (function (_super) {
  90792. __extends(LensFlaresOptimization, _super);
  90793. function LensFlaresOptimization() {
  90794. return _super !== null && _super.apply(this, arguments) || this;
  90795. }
  90796. /**
  90797. * Gets a string describing the action executed by the current optimization
  90798. * @return description string
  90799. */
  90800. LensFlaresOptimization.prototype.getDescription = function () {
  90801. return "Turning lens flares on/off";
  90802. };
  90803. /**
  90804. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90805. * @param scene defines the current scene where to apply this optimization
  90806. * @param optimizer defines the current optimizer
  90807. * @returns true if everything that can be done was applied
  90808. */
  90809. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90810. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90811. return true;
  90812. };
  90813. ;
  90814. return LensFlaresOptimization;
  90815. }(SceneOptimization));
  90816. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90817. /**
  90818. * Defines an optimization based on user defined callback.
  90819. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90820. */
  90821. var CustomOptimization = /** @class */ (function (_super) {
  90822. __extends(CustomOptimization, _super);
  90823. function CustomOptimization() {
  90824. return _super !== null && _super.apply(this, arguments) || this;
  90825. }
  90826. /**
  90827. * Gets a string describing the action executed by the current optimization
  90828. * @returns description string
  90829. */
  90830. CustomOptimization.prototype.getDescription = function () {
  90831. if (this.onGetDescription) {
  90832. return this.onGetDescription();
  90833. }
  90834. return "Running user defined callback";
  90835. };
  90836. /**
  90837. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90838. * @param scene defines the current scene where to apply this optimization
  90839. * @param optimizer defines the current optimizer
  90840. * @returns true if everything that can be done was applied
  90841. */
  90842. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90843. if (this.onApply) {
  90844. return this.onApply(scene, optimizer);
  90845. }
  90846. return true;
  90847. };
  90848. ;
  90849. return CustomOptimization;
  90850. }(SceneOptimization));
  90851. BABYLON.CustomOptimization = CustomOptimization;
  90852. /**
  90853. * Defines an optimization used to turn particles off
  90854. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90855. */
  90856. var ParticlesOptimization = /** @class */ (function (_super) {
  90857. __extends(ParticlesOptimization, _super);
  90858. function ParticlesOptimization() {
  90859. return _super !== null && _super.apply(this, arguments) || this;
  90860. }
  90861. /**
  90862. * Gets a string describing the action executed by the current optimization
  90863. * @return description string
  90864. */
  90865. ParticlesOptimization.prototype.getDescription = function () {
  90866. return "Turning particles on/off";
  90867. };
  90868. /**
  90869. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90870. * @param scene defines the current scene where to apply this optimization
  90871. * @param optimizer defines the current optimizer
  90872. * @returns true if everything that can be done was applied
  90873. */
  90874. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90875. scene.particlesEnabled = optimizer.isInImprovementMode;
  90876. return true;
  90877. };
  90878. ;
  90879. return ParticlesOptimization;
  90880. }(SceneOptimization));
  90881. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90882. /**
  90883. * Defines an optimization used to turn render targets off
  90884. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90885. */
  90886. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90887. __extends(RenderTargetsOptimization, _super);
  90888. function RenderTargetsOptimization() {
  90889. return _super !== null && _super.apply(this, arguments) || this;
  90890. }
  90891. /**
  90892. * Gets a string describing the action executed by the current optimization
  90893. * @return description string
  90894. */
  90895. RenderTargetsOptimization.prototype.getDescription = function () {
  90896. return "Turning render targets off";
  90897. };
  90898. /**
  90899. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90900. * @param scene defines the current scene where to apply this optimization
  90901. * @param optimizer defines the current optimizer
  90902. * @returns true if everything that can be done was applied
  90903. */
  90904. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90905. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90906. return true;
  90907. };
  90908. ;
  90909. return RenderTargetsOptimization;
  90910. }(SceneOptimization));
  90911. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90912. /**
  90913. * Defines an optimization used to merge meshes with compatible materials
  90914. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90915. */
  90916. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90917. __extends(MergeMeshesOptimization, _super);
  90918. function MergeMeshesOptimization() {
  90919. var _this = _super !== null && _super.apply(this, arguments) || this;
  90920. _this._canBeMerged = function (abstractMesh) {
  90921. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90922. return false;
  90923. }
  90924. var mesh = abstractMesh;
  90925. if (!mesh.isVisible || !mesh.isEnabled()) {
  90926. return false;
  90927. }
  90928. if (mesh.instances.length > 0) {
  90929. return false;
  90930. }
  90931. if (mesh.skeleton || mesh.hasLODLevels) {
  90932. return false;
  90933. }
  90934. if (mesh.parent) {
  90935. return false;
  90936. }
  90937. return true;
  90938. };
  90939. return _this;
  90940. }
  90941. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90942. /**
  90943. * Gets or sets a boolean which defines if optimization octree has to be updated
  90944. */
  90945. get: function () {
  90946. return MergeMeshesOptimization._UpdateSelectionTree;
  90947. },
  90948. /**
  90949. * Gets or sets a boolean which defines if optimization octree has to be updated
  90950. */
  90951. set: function (value) {
  90952. MergeMeshesOptimization._UpdateSelectionTree = value;
  90953. },
  90954. enumerable: true,
  90955. configurable: true
  90956. });
  90957. /**
  90958. * Gets a string describing the action executed by the current optimization
  90959. * @return description string
  90960. */
  90961. MergeMeshesOptimization.prototype.getDescription = function () {
  90962. return "Merging similar meshes together";
  90963. };
  90964. /**
  90965. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90966. * @param scene defines the current scene where to apply this optimization
  90967. * @param optimizer defines the current optimizer
  90968. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90969. * @returns true if everything that can be done was applied
  90970. */
  90971. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90972. var globalPool = scene.meshes.slice(0);
  90973. var globalLength = globalPool.length;
  90974. for (var index = 0; index < globalLength; index++) {
  90975. var currentPool = new Array();
  90976. var current = globalPool[index];
  90977. // Checks
  90978. if (!this._canBeMerged(current)) {
  90979. continue;
  90980. }
  90981. currentPool.push(current);
  90982. // Find compatible meshes
  90983. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90984. var otherMesh = globalPool[subIndex];
  90985. if (!this._canBeMerged(otherMesh)) {
  90986. continue;
  90987. }
  90988. if (otherMesh.material !== current.material) {
  90989. continue;
  90990. }
  90991. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90992. continue;
  90993. }
  90994. currentPool.push(otherMesh);
  90995. globalLength--;
  90996. globalPool.splice(subIndex, 1);
  90997. subIndex--;
  90998. }
  90999. if (currentPool.length < 2) {
  91000. continue;
  91001. }
  91002. // Merge meshes
  91003. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  91004. }
  91005. if (updateSelectionTree != undefined) {
  91006. if (updateSelectionTree) {
  91007. scene.createOrUpdateSelectionOctree();
  91008. }
  91009. }
  91010. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  91011. scene.createOrUpdateSelectionOctree();
  91012. }
  91013. return true;
  91014. };
  91015. ;
  91016. MergeMeshesOptimization._UpdateSelectionTree = false;
  91017. return MergeMeshesOptimization;
  91018. }(SceneOptimization));
  91019. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  91020. /**
  91021. * Defines a list of options used by SceneOptimizer
  91022. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91023. */
  91024. var SceneOptimizerOptions = /** @class */ (function () {
  91025. /**
  91026. * Creates a new list of options used by SceneOptimizer
  91027. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  91028. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  91029. */
  91030. function SceneOptimizerOptions(
  91031. /**
  91032. * Defines the target frame rate to reach (60 by default)
  91033. */
  91034. targetFrameRate,
  91035. /**
  91036. * Defines the interval between two checkes (2000ms by default)
  91037. */
  91038. trackerDuration) {
  91039. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  91040. if (trackerDuration === void 0) { trackerDuration = 2000; }
  91041. this.targetFrameRate = targetFrameRate;
  91042. this.trackerDuration = trackerDuration;
  91043. /**
  91044. * Gets the list of optimizations to apply
  91045. */
  91046. this.optimizations = new Array();
  91047. }
  91048. /**
  91049. * Add a new optimization
  91050. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  91051. * @returns the current SceneOptimizerOptions
  91052. */
  91053. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  91054. this.optimizations.push(optimization);
  91055. return this;
  91056. };
  91057. /**
  91058. * Add a new custom optimization
  91059. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  91060. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  91061. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  91062. * @returns the current SceneOptimizerOptions
  91063. */
  91064. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  91065. if (priority === void 0) { priority = 0; }
  91066. var optimization = new CustomOptimization(priority);
  91067. optimization.onApply = onApply;
  91068. optimization.onGetDescription = onGetDescription;
  91069. this.optimizations.push(optimization);
  91070. return this;
  91071. };
  91072. /**
  91073. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  91074. * @param targetFrameRate defines the target frame rate (60 by default)
  91075. * @returns a SceneOptimizerOptions object
  91076. */
  91077. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  91078. var result = new SceneOptimizerOptions(targetFrameRate);
  91079. var priority = 0;
  91080. result.addOptimization(new MergeMeshesOptimization(priority));
  91081. result.addOptimization(new ShadowsOptimization(priority));
  91082. result.addOptimization(new LensFlaresOptimization(priority));
  91083. // Next priority
  91084. priority++;
  91085. result.addOptimization(new PostProcessesOptimization(priority));
  91086. result.addOptimization(new ParticlesOptimization(priority));
  91087. // Next priority
  91088. priority++;
  91089. result.addOptimization(new TextureOptimization(priority, 1024));
  91090. return result;
  91091. };
  91092. /**
  91093. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  91094. * @param targetFrameRate defines the target frame rate (60 by default)
  91095. * @returns a SceneOptimizerOptions object
  91096. */
  91097. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  91098. var result = new SceneOptimizerOptions(targetFrameRate);
  91099. var priority = 0;
  91100. result.addOptimization(new MergeMeshesOptimization(priority));
  91101. result.addOptimization(new ShadowsOptimization(priority));
  91102. result.addOptimization(new LensFlaresOptimization(priority));
  91103. // Next priority
  91104. priority++;
  91105. result.addOptimization(new PostProcessesOptimization(priority));
  91106. result.addOptimization(new ParticlesOptimization(priority));
  91107. // Next priority
  91108. priority++;
  91109. result.addOptimization(new TextureOptimization(priority, 512));
  91110. // Next priority
  91111. priority++;
  91112. result.addOptimization(new RenderTargetsOptimization(priority));
  91113. // Next priority
  91114. priority++;
  91115. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  91116. return result;
  91117. };
  91118. /**
  91119. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  91120. * @param targetFrameRate defines the target frame rate (60 by default)
  91121. * @returns a SceneOptimizerOptions object
  91122. */
  91123. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  91124. var result = new SceneOptimizerOptions(targetFrameRate);
  91125. var priority = 0;
  91126. result.addOptimization(new MergeMeshesOptimization(priority));
  91127. result.addOptimization(new ShadowsOptimization(priority));
  91128. result.addOptimization(new LensFlaresOptimization(priority));
  91129. // Next priority
  91130. priority++;
  91131. result.addOptimization(new PostProcessesOptimization(priority));
  91132. result.addOptimization(new ParticlesOptimization(priority));
  91133. // Next priority
  91134. priority++;
  91135. result.addOptimization(new TextureOptimization(priority, 256));
  91136. // Next priority
  91137. priority++;
  91138. result.addOptimization(new RenderTargetsOptimization(priority));
  91139. // Next priority
  91140. priority++;
  91141. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  91142. return result;
  91143. };
  91144. return SceneOptimizerOptions;
  91145. }());
  91146. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  91147. /**
  91148. * Class used to run optimizations in order to reach a target frame rate
  91149. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91150. */
  91151. var SceneOptimizer = /** @class */ (function () {
  91152. /**
  91153. * Creates a new SceneOptimizer
  91154. * @param scene defines the scene to work on
  91155. * @param options defines the options to use with the SceneOptimizer
  91156. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  91157. * @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)
  91158. */
  91159. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  91160. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  91161. if (improvementMode === void 0) { improvementMode = false; }
  91162. var _this = this;
  91163. this._isRunning = false;
  91164. this._currentPriorityLevel = 0;
  91165. this._targetFrameRate = 60;
  91166. this._trackerDuration = 2000;
  91167. this._currentFrameRate = 0;
  91168. this._improvementMode = false;
  91169. /**
  91170. * Defines an observable called when the optimizer reaches the target frame rate
  91171. */
  91172. this.onSuccessObservable = new BABYLON.Observable();
  91173. /**
  91174. * Defines an observable called when the optimizer enables an optimization
  91175. */
  91176. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  91177. /**
  91178. * Defines an observable called when the optimizer is not able to reach the target frame rate
  91179. */
  91180. this.onFailureObservable = new BABYLON.Observable();
  91181. if (!options) {
  91182. this._options = new SceneOptimizerOptions();
  91183. }
  91184. else {
  91185. this._options = options;
  91186. }
  91187. if (this._options.targetFrameRate) {
  91188. this._targetFrameRate = this._options.targetFrameRate;
  91189. }
  91190. if (this._options.trackerDuration) {
  91191. this._trackerDuration = this._options.trackerDuration;
  91192. }
  91193. if (autoGeneratePriorities) {
  91194. var priority = 0;
  91195. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  91196. var optim = _a[_i];
  91197. optim.priority = priority++;
  91198. }
  91199. }
  91200. this._improvementMode = improvementMode;
  91201. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91202. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  91203. _this._sceneDisposeObserver = null;
  91204. _this.dispose();
  91205. });
  91206. }
  91207. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  91208. /**
  91209. * Gets a boolean indicating if the optimizer is in improvement mode
  91210. */
  91211. get: function () {
  91212. return this._improvementMode;
  91213. },
  91214. enumerable: true,
  91215. configurable: true
  91216. });
  91217. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  91218. /**
  91219. * Gets the current priority level (0 at start)
  91220. */
  91221. get: function () {
  91222. return this._currentPriorityLevel;
  91223. },
  91224. enumerable: true,
  91225. configurable: true
  91226. });
  91227. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  91228. /**
  91229. * Gets the current frame rate checked by the SceneOptimizer
  91230. */
  91231. get: function () {
  91232. return this._currentFrameRate;
  91233. },
  91234. enumerable: true,
  91235. configurable: true
  91236. });
  91237. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  91238. /**
  91239. * Gets or sets the current target frame rate (60 by default)
  91240. */
  91241. get: function () {
  91242. return this._targetFrameRate;
  91243. },
  91244. /**
  91245. * Gets or sets the current target frame rate (60 by default)
  91246. */
  91247. set: function (value) {
  91248. this._targetFrameRate = value;
  91249. },
  91250. enumerable: true,
  91251. configurable: true
  91252. });
  91253. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  91254. /**
  91255. * Gets or sets the current interval between two checks (every 2000ms by default)
  91256. */
  91257. get: function () {
  91258. return this._trackerDuration;
  91259. },
  91260. /**
  91261. * Gets or sets the current interval between two checks (every 2000ms by default)
  91262. */
  91263. set: function (value) {
  91264. this._trackerDuration = value;
  91265. },
  91266. enumerable: true,
  91267. configurable: true
  91268. });
  91269. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  91270. /**
  91271. * Gets the list of active optimizations
  91272. */
  91273. get: function () {
  91274. return this._options.optimizations;
  91275. },
  91276. enumerable: true,
  91277. configurable: true
  91278. });
  91279. /**
  91280. * Stops the current optimizer
  91281. */
  91282. SceneOptimizer.prototype.stop = function () {
  91283. this._isRunning = false;
  91284. };
  91285. /**
  91286. * Reset the optimizer to initial step (current priority level = 0)
  91287. */
  91288. SceneOptimizer.prototype.reset = function () {
  91289. this._currentPriorityLevel = 0;
  91290. };
  91291. /**
  91292. * Start the optimizer. By default it will try to reach a specific framerate
  91293. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  91294. */
  91295. SceneOptimizer.prototype.start = function () {
  91296. var _this = this;
  91297. if (this._isRunning) {
  91298. return;
  91299. }
  91300. this._isRunning = true;
  91301. // Let's wait for the scene to be ready before running our check
  91302. this._scene.executeWhenReady(function () {
  91303. setTimeout(function () {
  91304. _this._checkCurrentState();
  91305. }, _this._trackerDuration);
  91306. });
  91307. };
  91308. SceneOptimizer.prototype._checkCurrentState = function () {
  91309. var _this = this;
  91310. if (!this._isRunning) {
  91311. return;
  91312. }
  91313. var scene = this._scene;
  91314. var options = this._options;
  91315. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  91316. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  91317. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  91318. this._isRunning = false;
  91319. this.onSuccessObservable.notifyObservers(this);
  91320. return;
  91321. }
  91322. // Apply current level of optimizations
  91323. var allDone = true;
  91324. var noOptimizationApplied = true;
  91325. for (var index = 0; index < options.optimizations.length; index++) {
  91326. var optimization = options.optimizations[index];
  91327. if (optimization.priority === this._currentPriorityLevel) {
  91328. noOptimizationApplied = false;
  91329. allDone = allDone && optimization.apply(scene, this);
  91330. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  91331. }
  91332. }
  91333. // If no optimization was applied, this is a failure :(
  91334. if (noOptimizationApplied) {
  91335. this._isRunning = false;
  91336. this.onFailureObservable.notifyObservers(this);
  91337. return;
  91338. }
  91339. // If all optimizations were done, move to next level
  91340. if (allDone) {
  91341. this._currentPriorityLevel++;
  91342. }
  91343. // Let's the system running for a specific amount of time before checking FPS
  91344. scene.executeWhenReady(function () {
  91345. setTimeout(function () {
  91346. _this._checkCurrentState();
  91347. }, _this._trackerDuration);
  91348. });
  91349. };
  91350. /**
  91351. * Release all resources
  91352. */
  91353. SceneOptimizer.prototype.dispose = function () {
  91354. this.stop();
  91355. this.onSuccessObservable.clear();
  91356. this.onFailureObservable.clear();
  91357. this.onNewOptimizationAppliedObservable.clear();
  91358. if (this._sceneDisposeObserver) {
  91359. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91360. }
  91361. };
  91362. /**
  91363. * Helper function to create a SceneOptimizer with one single line of code
  91364. * @param scene defines the scene to work on
  91365. * @param options defines the options to use with the SceneOptimizer
  91366. * @param onSuccess defines a callback to call on success
  91367. * @param onFailure defines a callback to call on failure
  91368. * @returns the new SceneOptimizer object
  91369. */
  91370. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  91371. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  91372. if (onSuccess) {
  91373. optimizer.onSuccessObservable.add(function () {
  91374. onSuccess();
  91375. });
  91376. }
  91377. if (onFailure) {
  91378. optimizer.onFailureObservable.add(function () {
  91379. onFailure();
  91380. });
  91381. }
  91382. optimizer.start();
  91383. return optimizer;
  91384. };
  91385. return SceneOptimizer;
  91386. }());
  91387. BABYLON.SceneOptimizer = SceneOptimizer;
  91388. })(BABYLON || (BABYLON = {}));
  91389. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  91390. var BABYLON;
  91391. (function (BABYLON) {
  91392. var OutlineRenderer = /** @class */ (function () {
  91393. function OutlineRenderer(scene) {
  91394. this.zOffset = 1;
  91395. this._scene = scene;
  91396. }
  91397. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  91398. var _this = this;
  91399. if (useOverlay === void 0) { useOverlay = false; }
  91400. var scene = this._scene;
  91401. var engine = this._scene.getEngine();
  91402. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91403. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  91404. return;
  91405. }
  91406. var mesh = subMesh.getRenderingMesh();
  91407. var material = subMesh.getMaterial();
  91408. if (!material || !scene.activeCamera) {
  91409. return;
  91410. }
  91411. engine.enableEffect(this._effect);
  91412. // Logarithmic depth
  91413. if (material.useLogarithmicDepth) {
  91414. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  91415. }
  91416. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  91417. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  91418. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  91419. // Bones
  91420. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91421. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91422. }
  91423. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  91424. // Alpha test
  91425. if (material && material.needAlphaTesting()) {
  91426. var alphaTexture = material.getAlphaTestTexture();
  91427. if (alphaTexture) {
  91428. this._effect.setTexture("diffuseSampler", alphaTexture);
  91429. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  91430. }
  91431. }
  91432. engine.setZOffset(-this.zOffset);
  91433. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  91434. engine.setZOffset(0);
  91435. };
  91436. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  91437. var defines = [];
  91438. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  91439. var mesh = subMesh.getMesh();
  91440. var material = subMesh.getMaterial();
  91441. if (material) {
  91442. // Alpha test
  91443. if (material.needAlphaTesting()) {
  91444. defines.push("#define ALPHATEST");
  91445. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91446. attribs.push(BABYLON.VertexBuffer.UVKind);
  91447. defines.push("#define UV1");
  91448. }
  91449. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  91450. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91451. defines.push("#define UV2");
  91452. }
  91453. }
  91454. //Logarithmic depth
  91455. if (material.useLogarithmicDepth) {
  91456. defines.push("#define LOGARITHMICDEPTH");
  91457. }
  91458. }
  91459. // Bones
  91460. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91461. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91462. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91463. if (mesh.numBoneInfluencers > 4) {
  91464. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91465. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91466. }
  91467. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91468. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  91469. }
  91470. else {
  91471. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91472. }
  91473. // Instances
  91474. if (useInstances) {
  91475. defines.push("#define INSTANCES");
  91476. attribs.push("world0");
  91477. attribs.push("world1");
  91478. attribs.push("world2");
  91479. attribs.push("world3");
  91480. }
  91481. // Get correct effect
  91482. var join = defines.join("\n");
  91483. if (this._cachedDefines !== join) {
  91484. this._cachedDefines = join;
  91485. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  91486. }
  91487. return this._effect.isReady();
  91488. };
  91489. return OutlineRenderer;
  91490. }());
  91491. BABYLON.OutlineRenderer = OutlineRenderer;
  91492. })(BABYLON || (BABYLON = {}));
  91493. //# sourceMappingURL=babylon.outlineRenderer.js.map
  91494. var BABYLON;
  91495. (function (BABYLON) {
  91496. var FaceAdjacencies = /** @class */ (function () {
  91497. function FaceAdjacencies() {
  91498. this.edges = new Array();
  91499. this.edgesConnectedCount = 0;
  91500. }
  91501. return FaceAdjacencies;
  91502. }());
  91503. var EdgesRenderer = /** @class */ (function () {
  91504. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  91505. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  91506. if (epsilon === void 0) { epsilon = 0.95; }
  91507. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  91508. this.edgesWidthScalerForOrthographic = 1000.0;
  91509. this.edgesWidthScalerForPerspective = 50.0;
  91510. this._linesPositions = new Array();
  91511. this._linesNormals = new Array();
  91512. this._linesIndices = new Array();
  91513. this._buffers = {};
  91514. this._checkVerticesInsteadOfIndices = false;
  91515. this._source = source;
  91516. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  91517. this._epsilon = epsilon;
  91518. this._prepareRessources();
  91519. this._generateEdgesLines();
  91520. }
  91521. EdgesRenderer.prototype._prepareRessources = function () {
  91522. if (this._lineShader) {
  91523. return;
  91524. }
  91525. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  91526. attributes: ["position", "normal"],
  91527. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  91528. });
  91529. this._lineShader.disableDepthWrite = true;
  91530. this._lineShader.backFaceCulling = false;
  91531. };
  91532. EdgesRenderer.prototype._rebuild = function () {
  91533. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91534. if (buffer) {
  91535. buffer._rebuild();
  91536. }
  91537. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91538. if (buffer) {
  91539. buffer._rebuild();
  91540. }
  91541. var scene = this._source.getScene();
  91542. var engine = scene.getEngine();
  91543. this._ib = engine.createIndexBuffer(this._linesIndices);
  91544. };
  91545. EdgesRenderer.prototype.dispose = function () {
  91546. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91547. if (buffer) {
  91548. buffer.dispose();
  91549. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  91550. }
  91551. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91552. if (buffer) {
  91553. buffer.dispose();
  91554. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  91555. }
  91556. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  91557. this._lineShader.dispose();
  91558. };
  91559. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  91560. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  91561. return 0;
  91562. }
  91563. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  91564. return 1;
  91565. }
  91566. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  91567. return 2;
  91568. }
  91569. return -1;
  91570. };
  91571. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  91572. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  91573. return 0;
  91574. }
  91575. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  91576. return 1;
  91577. }
  91578. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  91579. return 2;
  91580. }
  91581. return -1;
  91582. };
  91583. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91584. var needToCreateLine;
  91585. if (edge === undefined) {
  91586. needToCreateLine = true;
  91587. }
  91588. else {
  91589. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91590. needToCreateLine = dotProduct < this._epsilon;
  91591. }
  91592. if (needToCreateLine) {
  91593. var offset = this._linesPositions.length / 3;
  91594. var normal = p0.subtract(p1);
  91595. normal.normalize();
  91596. // Positions
  91597. this._linesPositions.push(p0.x);
  91598. this._linesPositions.push(p0.y);
  91599. this._linesPositions.push(p0.z);
  91600. this._linesPositions.push(p0.x);
  91601. this._linesPositions.push(p0.y);
  91602. this._linesPositions.push(p0.z);
  91603. this._linesPositions.push(p1.x);
  91604. this._linesPositions.push(p1.y);
  91605. this._linesPositions.push(p1.z);
  91606. this._linesPositions.push(p1.x);
  91607. this._linesPositions.push(p1.y);
  91608. this._linesPositions.push(p1.z);
  91609. // Normals
  91610. this._linesNormals.push(p1.x);
  91611. this._linesNormals.push(p1.y);
  91612. this._linesNormals.push(p1.z);
  91613. this._linesNormals.push(-1);
  91614. this._linesNormals.push(p1.x);
  91615. this._linesNormals.push(p1.y);
  91616. this._linesNormals.push(p1.z);
  91617. this._linesNormals.push(1);
  91618. this._linesNormals.push(p0.x);
  91619. this._linesNormals.push(p0.y);
  91620. this._linesNormals.push(p0.z);
  91621. this._linesNormals.push(-1);
  91622. this._linesNormals.push(p0.x);
  91623. this._linesNormals.push(p0.y);
  91624. this._linesNormals.push(p0.z);
  91625. this._linesNormals.push(1);
  91626. // Indices
  91627. this._linesIndices.push(offset);
  91628. this._linesIndices.push(offset + 1);
  91629. this._linesIndices.push(offset + 2);
  91630. this._linesIndices.push(offset);
  91631. this._linesIndices.push(offset + 2);
  91632. this._linesIndices.push(offset + 3);
  91633. }
  91634. };
  91635. EdgesRenderer.prototype._generateEdgesLines = function () {
  91636. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91637. var indices = this._source.getIndices();
  91638. if (!indices || !positions) {
  91639. return;
  91640. }
  91641. // First let's find adjacencies
  91642. var adjacencies = new Array();
  91643. var faceNormals = new Array();
  91644. var index;
  91645. var faceAdjacencies;
  91646. // Prepare faces
  91647. for (index = 0; index < indices.length; index += 3) {
  91648. faceAdjacencies = new FaceAdjacencies();
  91649. var p0Index = indices[index];
  91650. var p1Index = indices[index + 1];
  91651. var p2Index = indices[index + 2];
  91652. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91653. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91654. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91655. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91656. faceNormal.normalize();
  91657. faceNormals.push(faceNormal);
  91658. adjacencies.push(faceAdjacencies);
  91659. }
  91660. // Scan
  91661. for (index = 0; index < adjacencies.length; index++) {
  91662. faceAdjacencies = adjacencies[index];
  91663. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91664. var otherFaceAdjacencies = adjacencies[otherIndex];
  91665. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91666. break;
  91667. }
  91668. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91669. continue;
  91670. }
  91671. var otherP0 = indices[otherIndex * 3];
  91672. var otherP1 = indices[otherIndex * 3 + 1];
  91673. var otherP2 = indices[otherIndex * 3 + 2];
  91674. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91675. var otherEdgeIndex = 0;
  91676. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91677. continue;
  91678. }
  91679. switch (edgeIndex) {
  91680. case 0:
  91681. if (this._checkVerticesInsteadOfIndices) {
  91682. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91683. }
  91684. else {
  91685. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91686. }
  91687. break;
  91688. case 1:
  91689. if (this._checkVerticesInsteadOfIndices) {
  91690. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91691. }
  91692. else {
  91693. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91694. }
  91695. break;
  91696. case 2:
  91697. if (this._checkVerticesInsteadOfIndices) {
  91698. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91699. }
  91700. else {
  91701. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91702. }
  91703. break;
  91704. }
  91705. if (otherEdgeIndex === -1) {
  91706. continue;
  91707. }
  91708. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91709. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91710. faceAdjacencies.edgesConnectedCount++;
  91711. otherFaceAdjacencies.edgesConnectedCount++;
  91712. if (faceAdjacencies.edgesConnectedCount === 3) {
  91713. break;
  91714. }
  91715. }
  91716. }
  91717. }
  91718. // Create lines
  91719. for (index = 0; index < adjacencies.length; index++) {
  91720. // 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
  91721. var current = adjacencies[index];
  91722. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91723. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91724. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91725. }
  91726. // Merge into a single mesh
  91727. var engine = this._source.getScene().getEngine();
  91728. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91729. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91730. this._ib = engine.createIndexBuffer(this._linesIndices);
  91731. this._indicesCount = this._linesIndices.length;
  91732. };
  91733. EdgesRenderer.prototype.render = function () {
  91734. var scene = this._source.getScene();
  91735. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91736. return;
  91737. }
  91738. var engine = scene.getEngine();
  91739. this._lineShader._preBind();
  91740. // VBOs
  91741. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91742. scene.resetCachedMaterial();
  91743. this._lineShader.setColor4("color", this._source.edgesColor);
  91744. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91745. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91746. }
  91747. else {
  91748. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91749. }
  91750. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91751. this._lineShader.bind(this._source.getWorldMatrix());
  91752. // Draw order
  91753. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91754. this._lineShader.unbind();
  91755. engine.setDepthWrite(true);
  91756. };
  91757. return EdgesRenderer;
  91758. }());
  91759. BABYLON.EdgesRenderer = EdgesRenderer;
  91760. })(BABYLON || (BABYLON = {}));
  91761. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91762. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91763. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91764. s = arguments[i];
  91765. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91766. t[p] = s[p];
  91767. }
  91768. return t;
  91769. };
  91770. var BABYLON;
  91771. (function (BABYLON) {
  91772. /**
  91773. * The effect layer Helps adding post process effect blended with the main pass.
  91774. *
  91775. * This can be for instance use to generate glow or higlight effects on the scene.
  91776. *
  91777. * The effect layer class can not be used directly and is intented to inherited from to be
  91778. * customized per effects.
  91779. */
  91780. var EffectLayer = /** @class */ (function () {
  91781. /**
  91782. * Instantiates a new effect Layer and references it in the scene.
  91783. * @param name The name of the layer
  91784. * @param scene The scene to use the layer in
  91785. */
  91786. function EffectLayer(
  91787. /** The Friendly of the effect in the scene */
  91788. name, scene) {
  91789. this._vertexBuffers = {};
  91790. this._maxSize = 0;
  91791. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91792. this._shouldRender = true;
  91793. this._postProcesses = [];
  91794. this._textures = [];
  91795. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91796. /**
  91797. * The clear color of the texture used to generate the glow map.
  91798. */
  91799. this.neutralColor = new BABYLON.Color4();
  91800. /**
  91801. * Specifies wether the highlight layer is enabled or not.
  91802. */
  91803. this.isEnabled = true;
  91804. /**
  91805. * An event triggered when the effect layer has been disposed.
  91806. */
  91807. this.onDisposeObservable = new BABYLON.Observable();
  91808. /**
  91809. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91810. */
  91811. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91812. /**
  91813. * An event triggered when the generated texture is being merged in the scene.
  91814. */
  91815. this.onBeforeComposeObservable = new BABYLON.Observable();
  91816. /**
  91817. * An event triggered when the generated texture has been merged in the scene.
  91818. */
  91819. this.onAfterComposeObservable = new BABYLON.Observable();
  91820. /**
  91821. * An event triggered when the efffect layer changes its size.
  91822. */
  91823. this.onSizeChangedObservable = new BABYLON.Observable();
  91824. this.name = name;
  91825. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91826. this._engine = scene.getEngine();
  91827. this._maxSize = this._engine.getCaps().maxTextureSize;
  91828. this._scene.effectLayers.push(this);
  91829. // Generate Buffers
  91830. this._generateIndexBuffer();
  91831. this._genrateVertexBuffer();
  91832. }
  91833. Object.defineProperty(EffectLayer.prototype, "camera", {
  91834. /**
  91835. * Gets the camera attached to the layer.
  91836. */
  91837. get: function () {
  91838. return this._effectLayerOptions.camera;
  91839. },
  91840. enumerable: true,
  91841. configurable: true
  91842. });
  91843. /**
  91844. * Initializes the effect layer with the required options.
  91845. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91846. */
  91847. EffectLayer.prototype._init = function (options) {
  91848. // Adapt options
  91849. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91850. this._setMainTextureSize();
  91851. this._createMainTexture();
  91852. this._createTextureAndPostProcesses();
  91853. this._mergeEffect = this._createMergeEffect();
  91854. };
  91855. /**
  91856. * Generates the index buffer of the full screen quad blending to the main canvas.
  91857. */
  91858. EffectLayer.prototype._generateIndexBuffer = function () {
  91859. // Indices
  91860. var indices = [];
  91861. indices.push(0);
  91862. indices.push(1);
  91863. indices.push(2);
  91864. indices.push(0);
  91865. indices.push(2);
  91866. indices.push(3);
  91867. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91868. };
  91869. /**
  91870. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91871. */
  91872. EffectLayer.prototype._genrateVertexBuffer = function () {
  91873. // VBO
  91874. var vertices = [];
  91875. vertices.push(1, 1);
  91876. vertices.push(-1, 1);
  91877. vertices.push(-1, -1);
  91878. vertices.push(1, -1);
  91879. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91880. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91881. };
  91882. /**
  91883. * Sets the main texture desired size which is the closest power of two
  91884. * of the engine canvas size.
  91885. */
  91886. EffectLayer.prototype._setMainTextureSize = function () {
  91887. if (this._effectLayerOptions.mainTextureFixedSize) {
  91888. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91889. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91890. }
  91891. else {
  91892. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91893. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91894. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91895. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91896. }
  91897. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91898. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91899. };
  91900. /**
  91901. * Creates the main texture for the effect layer.
  91902. */
  91903. EffectLayer.prototype._createMainTexture = function () {
  91904. var _this = this;
  91905. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91906. width: this._mainTextureDesiredSize.width,
  91907. height: this._mainTextureDesiredSize.height
  91908. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91909. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91910. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91911. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91912. this._mainTexture.anisotropicFilteringLevel = 1;
  91913. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91914. this._mainTexture.renderParticles = false;
  91915. this._mainTexture.renderList = null;
  91916. this._mainTexture.ignoreCameraViewport = true;
  91917. // Custom render function
  91918. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91919. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91920. var index;
  91921. var engine = _this._scene.getEngine();
  91922. if (depthOnlySubMeshes.length) {
  91923. engine.setColorWrite(false);
  91924. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91925. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91926. }
  91927. engine.setColorWrite(true);
  91928. }
  91929. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91930. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91931. }
  91932. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91933. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91934. }
  91935. for (index = 0; index < transparentSubMeshes.length; index++) {
  91936. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91937. }
  91938. };
  91939. this._mainTexture.onClearObservable.add(function (engine) {
  91940. engine.clear(_this.neutralColor, true, true, true);
  91941. });
  91942. };
  91943. /**
  91944. * Checks for the readiness of the element composing the layer.
  91945. * @param subMesh the mesh to check for
  91946. * @param useInstances specify wether or not to use instances to render the mesh
  91947. * @param emissiveTexture the associated emissive texture used to generate the glow
  91948. * @return true if ready otherwise, false
  91949. */
  91950. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91951. var material = subMesh.getMaterial();
  91952. if (!material) {
  91953. return false;
  91954. }
  91955. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91956. return false;
  91957. }
  91958. var defines = [];
  91959. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91960. var mesh = subMesh.getMesh();
  91961. var uv1 = false;
  91962. var uv2 = false;
  91963. // Alpha test
  91964. if (material && material.needAlphaTesting()) {
  91965. var alphaTexture = material.getAlphaTestTexture();
  91966. if (alphaTexture) {
  91967. defines.push("#define ALPHATEST");
  91968. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91969. alphaTexture.coordinatesIndex === 1) {
  91970. defines.push("#define DIFFUSEUV2");
  91971. uv2 = true;
  91972. }
  91973. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91974. defines.push("#define DIFFUSEUV1");
  91975. uv1 = true;
  91976. }
  91977. }
  91978. }
  91979. // Emissive
  91980. if (emissiveTexture) {
  91981. defines.push("#define EMISSIVE");
  91982. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91983. emissiveTexture.coordinatesIndex === 1) {
  91984. defines.push("#define EMISSIVEUV2");
  91985. uv2 = true;
  91986. }
  91987. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91988. defines.push("#define EMISSIVEUV1");
  91989. uv1 = true;
  91990. }
  91991. }
  91992. if (uv1) {
  91993. attribs.push(BABYLON.VertexBuffer.UVKind);
  91994. defines.push("#define UV1");
  91995. }
  91996. if (uv2) {
  91997. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91998. defines.push("#define UV2");
  91999. }
  92000. // Bones
  92001. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  92002. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  92003. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  92004. if (mesh.numBoneInfluencers > 4) {
  92005. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  92006. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  92007. }
  92008. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  92009. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  92010. }
  92011. else {
  92012. defines.push("#define NUM_BONE_INFLUENCERS 0");
  92013. }
  92014. // Morph targets
  92015. var manager = mesh.morphTargetManager;
  92016. var morphInfluencers = 0;
  92017. if (manager) {
  92018. if (manager.numInfluencers > 0) {
  92019. defines.push("#define MORPHTARGETS");
  92020. morphInfluencers = manager.numInfluencers;
  92021. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  92022. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  92023. }
  92024. }
  92025. // Instances
  92026. if (useInstances) {
  92027. defines.push("#define INSTANCES");
  92028. attribs.push("world0");
  92029. attribs.push("world1");
  92030. attribs.push("world2");
  92031. attribs.push("world3");
  92032. }
  92033. // Get correct effect
  92034. var join = defines.join("\n");
  92035. if (this._cachedDefines !== join) {
  92036. this._cachedDefines = join;
  92037. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  92038. }
  92039. return this._effectLayerMapGenerationEffect.isReady();
  92040. };
  92041. /**
  92042. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  92043. */
  92044. EffectLayer.prototype.render = function () {
  92045. var currentEffect = this._mergeEffect;
  92046. // Check
  92047. if (!currentEffect.isReady())
  92048. return;
  92049. for (var i = 0; i < this._postProcesses.length; i++) {
  92050. if (!this._postProcesses[i].isReady()) {
  92051. return;
  92052. }
  92053. }
  92054. var engine = this._scene.getEngine();
  92055. this.onBeforeComposeObservable.notifyObservers(this);
  92056. // Render
  92057. engine.enableEffect(currentEffect);
  92058. engine.setState(false);
  92059. // VBOs
  92060. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  92061. // Cache
  92062. var previousAlphaMode = engine.getAlphaMode();
  92063. // Go Blend.
  92064. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  92065. // Blends the map on the main canvas.
  92066. this._internalRender(currentEffect);
  92067. // Restore Alpha
  92068. engine.setAlphaMode(previousAlphaMode);
  92069. this.onAfterComposeObservable.notifyObservers(this);
  92070. // Handle size changes.
  92071. var size = this._mainTexture.getSize();
  92072. this._setMainTextureSize();
  92073. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  92074. // Recreate RTT and post processes on size change.
  92075. this.onSizeChangedObservable.notifyObservers(this);
  92076. this._disposeTextureAndPostProcesses();
  92077. this._createMainTexture();
  92078. this._createTextureAndPostProcesses();
  92079. }
  92080. };
  92081. /**
  92082. * Determine if a given mesh will be used in the current effect.
  92083. * @param mesh mesh to test
  92084. * @returns true if the mesh will be used
  92085. */
  92086. EffectLayer.prototype.hasMesh = function (mesh) {
  92087. return true;
  92088. };
  92089. /**
  92090. * Returns true if the layer contains information to display, otherwise false.
  92091. * @returns true if the glow layer should be rendered
  92092. */
  92093. EffectLayer.prototype.shouldRender = function () {
  92094. return this.isEnabled && this._shouldRender;
  92095. };
  92096. /**
  92097. * Returns true if the mesh should render, otherwise false.
  92098. * @param mesh The mesh to render
  92099. * @returns true if it should render otherwise false
  92100. */
  92101. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  92102. return true;
  92103. };
  92104. /**
  92105. * Returns true if the mesh should render, otherwise false.
  92106. * @param mesh The mesh to render
  92107. * @returns true if it should render otherwise false
  92108. */
  92109. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  92110. return true;
  92111. };
  92112. /**
  92113. * Renders the submesh passed in parameter to the generation map.
  92114. */
  92115. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  92116. var _this = this;
  92117. if (!this.shouldRender()) {
  92118. return;
  92119. }
  92120. var material = subMesh.getMaterial();
  92121. var mesh = subMesh.getRenderingMesh();
  92122. var scene = this._scene;
  92123. var engine = scene.getEngine();
  92124. if (!material) {
  92125. return;
  92126. }
  92127. // Do not block in blend mode.
  92128. if (material.needAlphaBlendingForMesh(mesh)) {
  92129. return;
  92130. }
  92131. // Culling
  92132. engine.setState(material.backFaceCulling);
  92133. // Managing instances
  92134. var batch = mesh._getInstancesRenderList(subMesh._id);
  92135. if (batch.mustReturn) {
  92136. return;
  92137. }
  92138. // Early Exit per mesh
  92139. if (!this._shouldRenderMesh(mesh)) {
  92140. return;
  92141. }
  92142. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  92143. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  92144. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  92145. engine.enableEffect(this._effectLayerMapGenerationEffect);
  92146. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  92147. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  92148. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  92149. // Alpha test
  92150. if (material && material.needAlphaTesting()) {
  92151. var alphaTexture = material.getAlphaTestTexture();
  92152. if (alphaTexture) {
  92153. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  92154. var textureMatrix = alphaTexture.getTextureMatrix();
  92155. if (textureMatrix) {
  92156. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  92157. }
  92158. }
  92159. }
  92160. // Glow emissive only
  92161. if (this._emissiveTextureAndColor.texture) {
  92162. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  92163. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  92164. }
  92165. // Bones
  92166. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  92167. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  92168. }
  92169. // Morph targets
  92170. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  92171. // Draw
  92172. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  92173. }
  92174. else {
  92175. // Need to reset refresh rate of the shadowMap
  92176. this._mainTexture.resetRefreshCounter();
  92177. }
  92178. };
  92179. /**
  92180. * Rebuild the required buffers.
  92181. * @hidden Internal use only.
  92182. */
  92183. EffectLayer.prototype._rebuild = function () {
  92184. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92185. if (vb) {
  92186. vb._rebuild();
  92187. }
  92188. this._generateIndexBuffer();
  92189. };
  92190. /**
  92191. * Dispose only the render target textures and post process.
  92192. */
  92193. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  92194. this._mainTexture.dispose();
  92195. for (var i = 0; i < this._postProcesses.length; i++) {
  92196. if (this._postProcesses[i]) {
  92197. this._postProcesses[i].dispose();
  92198. }
  92199. }
  92200. this._postProcesses = [];
  92201. for (var i = 0; i < this._textures.length; i++) {
  92202. if (this._textures[i]) {
  92203. this._textures[i].dispose();
  92204. }
  92205. }
  92206. this._textures = [];
  92207. };
  92208. /**
  92209. * Dispose the highlight layer and free resources.
  92210. */
  92211. EffectLayer.prototype.dispose = function () {
  92212. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92213. if (vertexBuffer) {
  92214. vertexBuffer.dispose();
  92215. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  92216. }
  92217. if (this._indexBuffer) {
  92218. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  92219. this._indexBuffer = null;
  92220. }
  92221. // Clean textures and post processes
  92222. this._disposeTextureAndPostProcesses();
  92223. // Remove from scene
  92224. var index = this._scene.effectLayers.indexOf(this, 0);
  92225. if (index > -1) {
  92226. this._scene.effectLayers.splice(index, 1);
  92227. }
  92228. // Callback
  92229. this.onDisposeObservable.notifyObservers(this);
  92230. this.onDisposeObservable.clear();
  92231. this.onBeforeRenderMainTextureObservable.clear();
  92232. this.onBeforeComposeObservable.clear();
  92233. this.onAfterComposeObservable.clear();
  92234. this.onSizeChangedObservable.clear();
  92235. };
  92236. /**
  92237. * Gets the class name of the effect layer
  92238. * @returns the string with the class name of the effect layer
  92239. */
  92240. EffectLayer.prototype.getClassName = function () {
  92241. return "EffectLayer";
  92242. };
  92243. /**
  92244. * Creates an effect layer from parsed effect layer data
  92245. * @param parsedEffectLayer defines effect layer data
  92246. * @param scene defines the current scene
  92247. * @param rootUrl defines the root URL containing the effect layer information
  92248. * @returns a parsed effect Layer
  92249. */
  92250. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  92251. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  92252. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  92253. };
  92254. __decorate([
  92255. BABYLON.serialize()
  92256. ], EffectLayer.prototype, "name", void 0);
  92257. __decorate([
  92258. BABYLON.serializeAsColor4()
  92259. ], EffectLayer.prototype, "neutralColor", void 0);
  92260. __decorate([
  92261. BABYLON.serialize()
  92262. ], EffectLayer.prototype, "isEnabled", void 0);
  92263. __decorate([
  92264. BABYLON.serializeAsCameraReference()
  92265. ], EffectLayer.prototype, "camera", null);
  92266. return EffectLayer;
  92267. }());
  92268. BABYLON.EffectLayer = EffectLayer;
  92269. })(BABYLON || (BABYLON = {}));
  92270. //# sourceMappingURL=babylon.effectLayer.js.map
  92271. var BABYLON;
  92272. (function (BABYLON) {
  92273. /**
  92274. * Special Glow Blur post process only blurring the alpha channel
  92275. * It enforces keeping the most luminous color in the color channel.
  92276. */
  92277. var GlowBlurPostProcess = /** @class */ (function (_super) {
  92278. __extends(GlowBlurPostProcess, _super);
  92279. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  92280. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  92281. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  92282. _this.direction = direction;
  92283. _this.kernel = kernel;
  92284. _this.onApplyObservable.add(function (effect) {
  92285. effect.setFloat2("screenSize", _this.width, _this.height);
  92286. effect.setVector2("direction", _this.direction);
  92287. effect.setFloat("blurWidth", _this.kernel);
  92288. });
  92289. return _this;
  92290. }
  92291. return GlowBlurPostProcess;
  92292. }(BABYLON.PostProcess));
  92293. /**
  92294. * The highlight layer Helps adding a glow effect around a mesh.
  92295. *
  92296. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92297. * glowy meshes to your scene.
  92298. *
  92299. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  92300. */
  92301. var HighlightLayer = /** @class */ (function (_super) {
  92302. __extends(HighlightLayer, _super);
  92303. /**
  92304. * Instantiates a new highlight Layer and references it to the scene..
  92305. * @param name The name of the layer
  92306. * @param scene The scene to use the layer in
  92307. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  92308. */
  92309. function HighlightLayer(name, scene, options) {
  92310. var _this = _super.call(this, name, scene) || this;
  92311. _this.name = name;
  92312. /**
  92313. * Specifies whether or not the inner glow is ACTIVE in the layer.
  92314. */
  92315. _this.innerGlow = true;
  92316. /**
  92317. * Specifies whether or not the outer glow is ACTIVE in the layer.
  92318. */
  92319. _this.outerGlow = true;
  92320. /**
  92321. * An event triggered when the highlight layer is being blurred.
  92322. */
  92323. _this.onBeforeBlurObservable = new BABYLON.Observable();
  92324. /**
  92325. * An event triggered when the highlight layer has been blurred.
  92326. */
  92327. _this.onAfterBlurObservable = new BABYLON.Observable();
  92328. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  92329. _this._meshes = {};
  92330. _this._excludedMeshes = {};
  92331. _this.neutralColor = HighlightLayer.NeutralColor;
  92332. // Warn on stencil
  92333. if (!_this._engine.isStencilEnable) {
  92334. 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 }");
  92335. }
  92336. // Adapt options
  92337. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92338. // Initialize the layer
  92339. _this._init({
  92340. alphaBlendingMode: _this._options.alphaBlendingMode,
  92341. camera: _this._options.camera,
  92342. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92343. mainTextureRatio: _this._options.mainTextureRatio
  92344. });
  92345. // Do not render as long as no meshes have been added
  92346. _this._shouldRender = false;
  92347. return _this;
  92348. }
  92349. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  92350. /**
  92351. * Gets the horizontal size of the blur.
  92352. */
  92353. get: function () {
  92354. return this._horizontalBlurPostprocess.kernel;
  92355. },
  92356. /**
  92357. * Specifies the horizontal size of the blur.
  92358. */
  92359. set: function (value) {
  92360. this._horizontalBlurPostprocess.kernel = value;
  92361. },
  92362. enumerable: true,
  92363. configurable: true
  92364. });
  92365. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  92366. /**
  92367. * Gets the vertical size of the blur.
  92368. */
  92369. get: function () {
  92370. return this._verticalBlurPostprocess.kernel;
  92371. },
  92372. /**
  92373. * Specifies the vertical size of the blur.
  92374. */
  92375. set: function (value) {
  92376. this._verticalBlurPostprocess.kernel = value;
  92377. },
  92378. enumerable: true,
  92379. configurable: true
  92380. });
  92381. /**
  92382. * Get the effect name of the layer.
  92383. * @return The effect name
  92384. */
  92385. HighlightLayer.prototype.getEffectName = function () {
  92386. return HighlightLayer.EffectName;
  92387. };
  92388. /**
  92389. * Create the merge effect. This is the shader use to blit the information back
  92390. * to the main canvas at the end of the scene rendering.
  92391. */
  92392. HighlightLayer.prototype._createMergeEffect = function () {
  92393. // Effect
  92394. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  92395. };
  92396. /**
  92397. * Creates the render target textures and post processes used in the highlight layer.
  92398. */
  92399. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  92400. var _this = this;
  92401. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  92402. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  92403. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92404. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92405. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  92406. width: blurTextureWidth,
  92407. height: blurTextureHeight
  92408. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92409. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92410. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92411. this._blurTexture.anisotropicFilteringLevel = 16;
  92412. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  92413. this._blurTexture.renderParticles = false;
  92414. this._blurTexture.ignoreCameraViewport = true;
  92415. this._textures = [this._blurTexture];
  92416. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  92417. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92418. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  92419. effect.setTexture("textureSampler", _this._mainTexture);
  92420. });
  92421. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92422. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92423. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92424. });
  92425. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92426. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  92427. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92428. });
  92429. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92430. }
  92431. else {
  92432. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  92433. width: blurTextureWidth,
  92434. height: blurTextureHeight
  92435. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92436. this._horizontalBlurPostprocess.width = blurTextureWidth;
  92437. this._horizontalBlurPostprocess.height = blurTextureHeight;
  92438. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92439. effect.setTexture("textureSampler", _this._mainTexture);
  92440. });
  92441. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  92442. width: blurTextureWidth,
  92443. height: blurTextureHeight
  92444. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92445. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92446. }
  92447. this._mainTexture.onAfterUnbindObservable.add(function () {
  92448. _this.onBeforeBlurObservable.notifyObservers(_this);
  92449. var internalTexture = _this._blurTexture.getInternalTexture();
  92450. if (internalTexture) {
  92451. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  92452. }
  92453. _this.onAfterBlurObservable.notifyObservers(_this);
  92454. });
  92455. // Prevent autoClear.
  92456. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92457. };
  92458. /**
  92459. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92460. */
  92461. HighlightLayer.prototype.needStencil = function () {
  92462. return true;
  92463. };
  92464. /**
  92465. * Checks for the readiness of the element composing the layer.
  92466. * @param subMesh the mesh to check for
  92467. * @param useInstances specify wether or not to use instances to render the mesh
  92468. * @param emissiveTexture the associated emissive texture used to generate the glow
  92469. * @return true if ready otherwise, false
  92470. */
  92471. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  92472. var material = subMesh.getMaterial();
  92473. var mesh = subMesh.getRenderingMesh();
  92474. if (!material || !mesh || !this._meshes) {
  92475. return false;
  92476. }
  92477. var emissiveTexture = null;
  92478. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92479. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92480. emissiveTexture = material.emissiveTexture;
  92481. }
  92482. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92483. };
  92484. /**
  92485. * Implementation specific of rendering the generating effect on the main canvas.
  92486. * @param effect The effect used to render through
  92487. */
  92488. HighlightLayer.prototype._internalRender = function (effect) {
  92489. // Texture
  92490. effect.setTexture("textureSampler", this._blurTexture);
  92491. // Cache
  92492. var engine = this._engine;
  92493. var previousStencilBuffer = engine.getStencilBuffer();
  92494. var previousStencilFunction = engine.getStencilFunction();
  92495. var previousStencilMask = engine.getStencilMask();
  92496. var previousStencilOperationPass = engine.getStencilOperationPass();
  92497. var previousStencilOperationFail = engine.getStencilOperationFail();
  92498. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  92499. var previousStencilReference = engine.getStencilFunctionReference();
  92500. // Stencil operations
  92501. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  92502. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  92503. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  92504. // Draw order
  92505. engine.setStencilMask(0x00);
  92506. engine.setStencilBuffer(true);
  92507. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  92508. // 2 passes inner outer
  92509. if (this.outerGlow) {
  92510. effect.setFloat("offset", 0);
  92511. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  92512. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92513. }
  92514. if (this.innerGlow) {
  92515. effect.setFloat("offset", 1);
  92516. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  92517. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92518. }
  92519. // Restore Cache
  92520. engine.setStencilFunction(previousStencilFunction);
  92521. engine.setStencilMask(previousStencilMask);
  92522. engine.setStencilBuffer(previousStencilBuffer);
  92523. engine.setStencilOperationPass(previousStencilOperationPass);
  92524. engine.setStencilOperationFail(previousStencilOperationFail);
  92525. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  92526. engine.setStencilFunctionReference(previousStencilReference);
  92527. };
  92528. /**
  92529. * Returns true if the layer contains information to display, otherwise false.
  92530. */
  92531. HighlightLayer.prototype.shouldRender = function () {
  92532. if (_super.prototype.shouldRender.call(this)) {
  92533. return this._meshes ? true : false;
  92534. }
  92535. return false;
  92536. };
  92537. /**
  92538. * Returns true if the mesh should render, otherwise false.
  92539. * @param mesh The mesh to render
  92540. * @returns true if it should render otherwise false
  92541. */
  92542. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  92543. // Excluded Mesh
  92544. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  92545. return false;
  92546. }
  92547. ;
  92548. return true;
  92549. };
  92550. /**
  92551. * Sets the required values for both the emissive texture and and the main color.
  92552. */
  92553. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92554. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92555. if (highlightLayerMesh) {
  92556. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  92557. }
  92558. else {
  92559. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92560. }
  92561. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92562. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92563. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  92564. }
  92565. else {
  92566. this._emissiveTextureAndColor.texture = null;
  92567. }
  92568. };
  92569. /**
  92570. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  92571. * @param mesh The mesh to exclude from the highlight layer
  92572. */
  92573. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  92574. if (!this._excludedMeshes) {
  92575. return;
  92576. }
  92577. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92578. if (!meshExcluded) {
  92579. this._excludedMeshes[mesh.uniqueId] = {
  92580. mesh: mesh,
  92581. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92582. mesh.getEngine().setStencilBuffer(false);
  92583. }),
  92584. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92585. mesh.getEngine().setStencilBuffer(true);
  92586. }),
  92587. };
  92588. }
  92589. };
  92590. /**
  92591. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92592. * @param mesh The mesh to highlight
  92593. */
  92594. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92595. if (!this._excludedMeshes) {
  92596. return;
  92597. }
  92598. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92599. if (meshExcluded) {
  92600. if (meshExcluded.beforeRender) {
  92601. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92602. }
  92603. if (meshExcluded.afterRender) {
  92604. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92605. }
  92606. }
  92607. this._excludedMeshes[mesh.uniqueId] = null;
  92608. };
  92609. /**
  92610. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92611. * @param mesh mesh to test
  92612. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92613. */
  92614. HighlightLayer.prototype.hasMesh = function (mesh) {
  92615. if (!this._meshes) {
  92616. return false;
  92617. }
  92618. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92619. };
  92620. /**
  92621. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92622. * @param mesh The mesh to highlight
  92623. * @param color The color of the highlight
  92624. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92625. */
  92626. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92627. var _this = this;
  92628. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92629. if (!this._meshes) {
  92630. return;
  92631. }
  92632. var meshHighlight = this._meshes[mesh.uniqueId];
  92633. if (meshHighlight) {
  92634. meshHighlight.color = color;
  92635. }
  92636. else {
  92637. this._meshes[mesh.uniqueId] = {
  92638. mesh: mesh,
  92639. color: color,
  92640. // Lambda required for capture due to Observable this context
  92641. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92642. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92643. _this._defaultStencilReference(mesh);
  92644. }
  92645. else {
  92646. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92647. }
  92648. }),
  92649. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92650. glowEmissiveOnly: glowEmissiveOnly
  92651. };
  92652. }
  92653. this._shouldRender = true;
  92654. };
  92655. /**
  92656. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92657. * @param mesh The mesh to highlight
  92658. */
  92659. HighlightLayer.prototype.removeMesh = function (mesh) {
  92660. if (!this._meshes) {
  92661. return;
  92662. }
  92663. var meshHighlight = this._meshes[mesh.uniqueId];
  92664. if (meshHighlight) {
  92665. if (meshHighlight.observerHighlight) {
  92666. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92667. }
  92668. if (meshHighlight.observerDefault) {
  92669. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92670. }
  92671. delete this._meshes[mesh.uniqueId];
  92672. }
  92673. this._shouldRender = false;
  92674. for (var meshHighlightToCheck in this._meshes) {
  92675. if (this._meshes[meshHighlightToCheck]) {
  92676. this._shouldRender = true;
  92677. break;
  92678. }
  92679. }
  92680. };
  92681. /**
  92682. * Force the stencil to the normal expected value for none glowing parts
  92683. */
  92684. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92685. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92686. };
  92687. /**
  92688. * Free any resources and references associated to a mesh.
  92689. * Internal use
  92690. * @param mesh The mesh to free.
  92691. */
  92692. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92693. this.removeMesh(mesh);
  92694. this.removeExcludedMesh(mesh);
  92695. };
  92696. /**
  92697. * Dispose the highlight layer and free resources.
  92698. */
  92699. HighlightLayer.prototype.dispose = function () {
  92700. if (this._meshes) {
  92701. // Clean mesh references
  92702. for (var id in this._meshes) {
  92703. var meshHighlight = this._meshes[id];
  92704. if (meshHighlight && meshHighlight.mesh) {
  92705. if (meshHighlight.observerHighlight) {
  92706. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92707. }
  92708. if (meshHighlight.observerDefault) {
  92709. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92710. }
  92711. }
  92712. }
  92713. this._meshes = null;
  92714. }
  92715. if (this._excludedMeshes) {
  92716. for (var id in this._excludedMeshes) {
  92717. var meshHighlight = this._excludedMeshes[id];
  92718. if (meshHighlight) {
  92719. if (meshHighlight.beforeRender) {
  92720. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92721. }
  92722. if (meshHighlight.afterRender) {
  92723. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92724. }
  92725. }
  92726. }
  92727. this._excludedMeshes = null;
  92728. }
  92729. _super.prototype.dispose.call(this);
  92730. };
  92731. /**
  92732. * Gets the class name of the effect layer
  92733. * @returns the string with the class name of the effect layer
  92734. */
  92735. HighlightLayer.prototype.getClassName = function () {
  92736. return "HighlightLayer";
  92737. };
  92738. /**
  92739. * Serializes this Highlight layer
  92740. * @returns a serialized Highlight layer object
  92741. */
  92742. HighlightLayer.prototype.serialize = function () {
  92743. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92744. serializationObject.customType = "BABYLON.HighlightLayer";
  92745. // Highlighted meshes
  92746. serializationObject.meshes = [];
  92747. if (this._meshes) {
  92748. for (var m in this._meshes) {
  92749. var mesh = this._meshes[m];
  92750. if (mesh) {
  92751. serializationObject.meshes.push({
  92752. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92753. color: mesh.color.asArray(),
  92754. meshId: mesh.mesh.id
  92755. });
  92756. }
  92757. }
  92758. }
  92759. // Excluded meshes
  92760. serializationObject.excludedMeshes = [];
  92761. if (this._excludedMeshes) {
  92762. for (var e in this._excludedMeshes) {
  92763. var excludedMesh = this._excludedMeshes[e];
  92764. if (excludedMesh) {
  92765. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92766. }
  92767. }
  92768. }
  92769. return serializationObject;
  92770. };
  92771. /**
  92772. * Creates a Highlight layer from parsed Highlight layer data
  92773. * @param parsedHightlightLayer defines the Highlight layer data
  92774. * @param scene defines the current scene
  92775. * @param rootUrl defines the root URL containing the Highlight layer information
  92776. * @returns a parsed Highlight layer
  92777. */
  92778. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92779. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92780. var index;
  92781. // Excluded meshes
  92782. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92783. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92784. if (mesh) {
  92785. hl.addExcludedMesh(mesh);
  92786. }
  92787. }
  92788. // Included meshes
  92789. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92790. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92791. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92792. if (mesh) {
  92793. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92794. }
  92795. }
  92796. return hl;
  92797. };
  92798. /**
  92799. * Effect Name of the highlight layer.
  92800. */
  92801. HighlightLayer.EffectName = "HighlightLayer";
  92802. /**
  92803. * The neutral color used during the preparation of the glow effect.
  92804. * This is black by default as the blend operation is a blend operation.
  92805. */
  92806. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92807. /**
  92808. * Stencil value used for glowing meshes.
  92809. */
  92810. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92811. /**
  92812. * Stencil value used for the other meshes in the scene.
  92813. */
  92814. HighlightLayer.NormalMeshStencilReference = 0x01;
  92815. __decorate([
  92816. BABYLON.serialize()
  92817. ], HighlightLayer.prototype, "innerGlow", void 0);
  92818. __decorate([
  92819. BABYLON.serialize()
  92820. ], HighlightLayer.prototype, "outerGlow", void 0);
  92821. __decorate([
  92822. BABYLON.serialize()
  92823. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92824. __decorate([
  92825. BABYLON.serialize()
  92826. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92827. __decorate([
  92828. BABYLON.serialize("options")
  92829. ], HighlightLayer.prototype, "_options", void 0);
  92830. return HighlightLayer;
  92831. }(BABYLON.EffectLayer));
  92832. BABYLON.HighlightLayer = HighlightLayer;
  92833. })(BABYLON || (BABYLON = {}));
  92834. //# sourceMappingURL=babylon.highlightLayer.js.map
  92835. var BABYLON;
  92836. (function (BABYLON) {
  92837. /**
  92838. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92839. *
  92840. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92841. * glowy meshes to your scene.
  92842. *
  92843. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92844. */
  92845. var GlowLayer = /** @class */ (function (_super) {
  92846. __extends(GlowLayer, _super);
  92847. /**
  92848. * Instantiates a new glow Layer and references it to the scene.
  92849. * @param name The name of the layer
  92850. * @param scene The scene to use the layer in
  92851. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92852. */
  92853. function GlowLayer(name, scene, options) {
  92854. var _this = _super.call(this, name, scene) || this;
  92855. _this._intensity = 1.0;
  92856. _this._includedOnlyMeshes = [];
  92857. _this._excludedMeshes = [];
  92858. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92859. // Adapt options
  92860. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92861. // Initialize the layer
  92862. _this._init({
  92863. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92864. camera: _this._options.camera,
  92865. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92866. mainTextureRatio: _this._options.mainTextureRatio
  92867. });
  92868. return _this;
  92869. }
  92870. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92871. /**
  92872. * Gets the kernel size of the blur.
  92873. */
  92874. get: function () {
  92875. return this._horizontalBlurPostprocess1.kernel;
  92876. },
  92877. /**
  92878. * Sets the kernel size of the blur.
  92879. */
  92880. set: function (value) {
  92881. this._horizontalBlurPostprocess1.kernel = value;
  92882. this._verticalBlurPostprocess1.kernel = value;
  92883. this._horizontalBlurPostprocess2.kernel = value;
  92884. this._verticalBlurPostprocess2.kernel = value;
  92885. },
  92886. enumerable: true,
  92887. configurable: true
  92888. });
  92889. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92890. /**
  92891. * Gets the glow intensity.
  92892. */
  92893. get: function () {
  92894. return this._intensity;
  92895. },
  92896. /**
  92897. * Sets the glow intensity.
  92898. */
  92899. set: function (value) {
  92900. this._intensity = value;
  92901. },
  92902. enumerable: true,
  92903. configurable: true
  92904. });
  92905. /**
  92906. * Get the effect name of the layer.
  92907. * @return The effect name
  92908. */
  92909. GlowLayer.prototype.getEffectName = function () {
  92910. return GlowLayer.EffectName;
  92911. };
  92912. /**
  92913. * Create the merge effect. This is the shader use to blit the information back
  92914. * to the main canvas at the end of the scene rendering.
  92915. */
  92916. GlowLayer.prototype._createMergeEffect = function () {
  92917. // Effect
  92918. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92919. };
  92920. /**
  92921. * Creates the render target textures and post processes used in the glow layer.
  92922. */
  92923. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92924. var _this = this;
  92925. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92926. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92927. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92928. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92929. var textureType = 0;
  92930. if (this._engine.getCaps().textureHalfFloatRender) {
  92931. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92932. }
  92933. else {
  92934. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92935. }
  92936. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92937. width: blurTextureWidth,
  92938. height: blurTextureHeight
  92939. }, this._scene, false, true, textureType);
  92940. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92941. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92942. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92943. this._blurTexture1.renderParticles = false;
  92944. this._blurTexture1.ignoreCameraViewport = true;
  92945. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92946. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92947. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92948. width: blurTextureWidth2,
  92949. height: blurTextureHeight2
  92950. }, this._scene, false, true, textureType);
  92951. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92952. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92953. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92954. this._blurTexture2.renderParticles = false;
  92955. this._blurTexture2.ignoreCameraViewport = true;
  92956. this._textures = [this._blurTexture1, this._blurTexture2];
  92957. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92958. width: blurTextureWidth,
  92959. height: blurTextureHeight
  92960. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92961. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92962. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92963. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92964. effect.setTexture("textureSampler", _this._mainTexture);
  92965. });
  92966. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92967. width: blurTextureWidth,
  92968. height: blurTextureHeight
  92969. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92970. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92971. width: blurTextureWidth2,
  92972. height: blurTextureHeight2
  92973. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92974. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92975. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92976. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92977. effect.setTexture("textureSampler", _this._blurTexture1);
  92978. });
  92979. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92980. width: blurTextureWidth2,
  92981. height: blurTextureHeight2
  92982. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92983. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92984. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92985. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92986. this._mainTexture.samples = this._options.mainTextureSamples;
  92987. this._mainTexture.onAfterUnbindObservable.add(function () {
  92988. var internalTexture = _this._blurTexture1.getInternalTexture();
  92989. if (internalTexture) {
  92990. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92991. internalTexture = _this._blurTexture2.getInternalTexture();
  92992. if (internalTexture) {
  92993. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92994. }
  92995. }
  92996. });
  92997. // Prevent autoClear.
  92998. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92999. };
  93000. /**
  93001. * Checks for the readiness of the element composing the layer.
  93002. * @param subMesh the mesh to check for
  93003. * @param useInstances specify wether or not to use instances to render the mesh
  93004. * @param emissiveTexture the associated emissive texture used to generate the glow
  93005. * @return true if ready otherwise, false
  93006. */
  93007. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  93008. var material = subMesh.getMaterial();
  93009. var mesh = subMesh.getRenderingMesh();
  93010. if (!material || !mesh) {
  93011. return false;
  93012. }
  93013. var emissiveTexture = material.emissiveTexture;
  93014. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  93015. };
  93016. /**
  93017. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  93018. */
  93019. GlowLayer.prototype.needStencil = function () {
  93020. return false;
  93021. };
  93022. /**
  93023. * Implementation specific of rendering the generating effect on the main canvas.
  93024. * @param effect The effect used to render through
  93025. */
  93026. GlowLayer.prototype._internalRender = function (effect) {
  93027. // Texture
  93028. effect.setTexture("textureSampler", this._blurTexture1);
  93029. effect.setTexture("textureSampler2", this._blurTexture2);
  93030. effect.setFloat("offset", this._intensity);
  93031. // Cache
  93032. var engine = this._engine;
  93033. var previousStencilBuffer = engine.getStencilBuffer();
  93034. // Draw order
  93035. engine.setStencilBuffer(false);
  93036. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93037. // Draw order
  93038. engine.setStencilBuffer(previousStencilBuffer);
  93039. };
  93040. /**
  93041. * Sets the required values for both the emissive texture and and the main color.
  93042. */
  93043. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  93044. var textureLevel = 1.0;
  93045. if (this.customEmissiveTextureSelector) {
  93046. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  93047. }
  93048. else {
  93049. if (material) {
  93050. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  93051. if (this._emissiveTextureAndColor.texture) {
  93052. textureLevel = this._emissiveTextureAndColor.texture.level;
  93053. }
  93054. }
  93055. else {
  93056. this._emissiveTextureAndColor.texture = null;
  93057. }
  93058. }
  93059. if (this.customEmissiveColorSelector) {
  93060. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  93061. }
  93062. else {
  93063. if (material.emissiveColor) {
  93064. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  93065. }
  93066. else {
  93067. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  93068. }
  93069. }
  93070. };
  93071. /**
  93072. * Returns true if the mesh should render, otherwise false.
  93073. * @param mesh The mesh to render
  93074. * @returns true if it should render otherwise false
  93075. */
  93076. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  93077. return this.hasMesh(mesh);
  93078. };
  93079. /**
  93080. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  93081. * @param mesh The mesh to exclude from the glow layer
  93082. */
  93083. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  93084. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  93085. this._excludedMeshes.push(mesh.uniqueId);
  93086. }
  93087. };
  93088. /**
  93089. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  93090. * @param mesh The mesh to remove
  93091. */
  93092. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  93093. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  93094. if (index !== -1) {
  93095. this._excludedMeshes.splice(index, 1);
  93096. }
  93097. };
  93098. /**
  93099. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  93100. * @param mesh The mesh to include in the glow layer
  93101. */
  93102. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  93103. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  93104. this._includedOnlyMeshes.push(mesh.uniqueId);
  93105. }
  93106. };
  93107. /**
  93108. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  93109. * @param mesh The mesh to remove
  93110. */
  93111. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  93112. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  93113. if (index !== -1) {
  93114. this._includedOnlyMeshes.splice(index, 1);
  93115. }
  93116. };
  93117. /**
  93118. * Determine if a given mesh will be used in the glow layer
  93119. * @param mesh The mesh to test
  93120. * @returns true if the mesh will be highlighted by the current glow layer
  93121. */
  93122. GlowLayer.prototype.hasMesh = function (mesh) {
  93123. // Included Mesh
  93124. if (this._includedOnlyMeshes.length) {
  93125. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  93126. }
  93127. ;
  93128. // Excluded Mesh
  93129. if (this._excludedMeshes.length) {
  93130. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  93131. }
  93132. ;
  93133. return true;
  93134. };
  93135. /**
  93136. * Free any resources and references associated to a mesh.
  93137. * Internal use
  93138. * @param mesh The mesh to free.
  93139. */
  93140. GlowLayer.prototype._disposeMesh = function (mesh) {
  93141. this.removeIncludedOnlyMesh(mesh);
  93142. this.removeExcludedMesh(mesh);
  93143. };
  93144. /**
  93145. * Gets the class name of the effect layer
  93146. * @returns the string with the class name of the effect layer
  93147. */
  93148. GlowLayer.prototype.getClassName = function () {
  93149. return "GlowLayer";
  93150. };
  93151. /**
  93152. * Serializes this glow layer
  93153. * @returns a serialized glow layer object
  93154. */
  93155. GlowLayer.prototype.serialize = function () {
  93156. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  93157. serializationObject.customType = "BABYLON.GlowLayer";
  93158. var index;
  93159. // Included meshes
  93160. serializationObject.includedMeshes = [];
  93161. if (this._includedOnlyMeshes.length) {
  93162. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  93163. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  93164. if (mesh) {
  93165. serializationObject.includedMeshes.push(mesh.id);
  93166. }
  93167. }
  93168. }
  93169. // Excluded meshes
  93170. serializationObject.excludedMeshes = [];
  93171. if (this._excludedMeshes.length) {
  93172. for (index = 0; index < this._excludedMeshes.length; index++) {
  93173. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  93174. if (mesh) {
  93175. serializationObject.excludedMeshes.push(mesh.id);
  93176. }
  93177. }
  93178. }
  93179. return serializationObject;
  93180. };
  93181. /**
  93182. * Creates a Glow Layer from parsed glow layer data
  93183. * @param parsedGlowLayer defines glow layer data
  93184. * @param scene defines the current scene
  93185. * @param rootUrl defines the root URL containing the glow layer information
  93186. * @returns a parsed Glow Layer
  93187. */
  93188. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  93189. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  93190. var index;
  93191. // Excluded meshes
  93192. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  93193. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  93194. if (mesh) {
  93195. gl.addExcludedMesh(mesh);
  93196. }
  93197. }
  93198. // Included meshes
  93199. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  93200. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  93201. if (mesh) {
  93202. gl.addIncludedOnlyMesh(mesh);
  93203. }
  93204. }
  93205. return gl;
  93206. };
  93207. /**
  93208. * Effect Name of the layer.
  93209. */
  93210. GlowLayer.EffectName = "GlowLayer";
  93211. /**
  93212. * The default blur kernel size used for the glow.
  93213. */
  93214. GlowLayer.DefaultBlurKernelSize = 32;
  93215. /**
  93216. * The default texture size ratio used for the glow.
  93217. */
  93218. GlowLayer.DefaultTextureRatio = 0.5;
  93219. __decorate([
  93220. BABYLON.serialize()
  93221. ], GlowLayer.prototype, "blurKernelSize", null);
  93222. __decorate([
  93223. BABYLON.serialize()
  93224. ], GlowLayer.prototype, "intensity", null);
  93225. __decorate([
  93226. BABYLON.serialize("options")
  93227. ], GlowLayer.prototype, "_options", void 0);
  93228. return GlowLayer;
  93229. }(BABYLON.EffectLayer));
  93230. BABYLON.GlowLayer = GlowLayer;
  93231. })(BABYLON || (BABYLON = {}));
  93232. //# sourceMappingURL=babylon.glowLayer.js.map
  93233. var BABYLON;
  93234. (function (BABYLON) {
  93235. /**
  93236. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  93237. */
  93238. var AssetTaskState;
  93239. (function (AssetTaskState) {
  93240. /**
  93241. * Initialization
  93242. */
  93243. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  93244. /**
  93245. * Running
  93246. */
  93247. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  93248. /**
  93249. * Done
  93250. */
  93251. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  93252. /**
  93253. * Error
  93254. */
  93255. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  93256. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  93257. /**
  93258. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  93259. */
  93260. var AbstractAssetTask = /** @class */ (function () {
  93261. /**
  93262. * Creates a new {BABYLON.AssetsManager}
  93263. * @param name defines the name of the task
  93264. */
  93265. function AbstractAssetTask(
  93266. /**
  93267. * Task name
  93268. */ name) {
  93269. this.name = name;
  93270. this._isCompleted = false;
  93271. this._taskState = AssetTaskState.INIT;
  93272. }
  93273. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  93274. /**
  93275. * Get if the task is completed
  93276. */
  93277. get: function () {
  93278. return this._isCompleted;
  93279. },
  93280. enumerable: true,
  93281. configurable: true
  93282. });
  93283. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  93284. /**
  93285. * Gets the current state of the task
  93286. */
  93287. get: function () {
  93288. return this._taskState;
  93289. },
  93290. enumerable: true,
  93291. configurable: true
  93292. });
  93293. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  93294. /**
  93295. * Gets the current error object (if task is in error)
  93296. */
  93297. get: function () {
  93298. return this._errorObject;
  93299. },
  93300. enumerable: true,
  93301. configurable: true
  93302. });
  93303. /**
  93304. * Internal only
  93305. * @hidden
  93306. */
  93307. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  93308. if (this._errorObject) {
  93309. return;
  93310. }
  93311. this._errorObject = {
  93312. message: message,
  93313. exception: exception
  93314. };
  93315. };
  93316. /**
  93317. * Execute the current task
  93318. * @param scene defines the scene where you want your assets to be loaded
  93319. * @param onSuccess is a callback called when the task is successfully executed
  93320. * @param onError is a callback called if an error occurs
  93321. */
  93322. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93323. var _this = this;
  93324. this._taskState = AssetTaskState.RUNNING;
  93325. this.runTask(scene, function () {
  93326. _this.onDoneCallback(onSuccess, onError);
  93327. }, function (msg, exception) {
  93328. _this.onErrorCallback(onError, msg, exception);
  93329. });
  93330. };
  93331. /**
  93332. * Execute the current task
  93333. * @param scene defines the scene where you want your assets to be loaded
  93334. * @param onSuccess is a callback called when the task is successfully executed
  93335. * @param onError is a callback called if an error occurs
  93336. */
  93337. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93338. throw new Error("runTask is not implemented");
  93339. };
  93340. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  93341. this._taskState = AssetTaskState.ERROR;
  93342. this._errorObject = {
  93343. message: message,
  93344. exception: exception
  93345. };
  93346. if (this.onError) {
  93347. this.onError(this, message, exception);
  93348. }
  93349. onError();
  93350. };
  93351. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  93352. try {
  93353. this._taskState = AssetTaskState.DONE;
  93354. this._isCompleted = true;
  93355. if (this.onSuccess) {
  93356. this.onSuccess(this);
  93357. }
  93358. onSuccess();
  93359. }
  93360. catch (e) {
  93361. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  93362. }
  93363. };
  93364. return AbstractAssetTask;
  93365. }());
  93366. BABYLON.AbstractAssetTask = AbstractAssetTask;
  93367. /**
  93368. * Class used to share progress information about assets loading
  93369. */
  93370. var AssetsProgressEvent = /** @class */ (function () {
  93371. /**
  93372. * Creates a {BABYLON.AssetsProgressEvent}
  93373. * @param remainingCount defines the number of remaining tasks to process
  93374. * @param totalCount defines the total number of tasks
  93375. * @param task defines the task that was just processed
  93376. */
  93377. function AssetsProgressEvent(remainingCount, totalCount, task) {
  93378. this.remainingCount = remainingCount;
  93379. this.totalCount = totalCount;
  93380. this.task = task;
  93381. }
  93382. return AssetsProgressEvent;
  93383. }());
  93384. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  93385. /**
  93386. * Define a task used by {BABYLON.AssetsManager} to load meshes
  93387. */
  93388. var MeshAssetTask = /** @class */ (function (_super) {
  93389. __extends(MeshAssetTask, _super);
  93390. /**
  93391. * Creates a new {BABYLON.MeshAssetTask}
  93392. * @param name defines the name of the task
  93393. * @param meshesNames defines the list of mesh's names you want to load
  93394. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  93395. * @param sceneFilename defines the filename of the scene to load from
  93396. */
  93397. function MeshAssetTask(
  93398. /**
  93399. * Defines the name of the task
  93400. */
  93401. name,
  93402. /**
  93403. * Defines the list of mesh's names you want to load
  93404. */
  93405. meshesNames,
  93406. /**
  93407. * Defines the root url to use as a base to load your meshes and associated resources
  93408. */
  93409. rootUrl,
  93410. /**
  93411. * Defines the filename of the scene to load from
  93412. */
  93413. sceneFilename) {
  93414. var _this = _super.call(this, name) || this;
  93415. _this.name = name;
  93416. _this.meshesNames = meshesNames;
  93417. _this.rootUrl = rootUrl;
  93418. _this.sceneFilename = sceneFilename;
  93419. return _this;
  93420. }
  93421. /**
  93422. * Execute the current task
  93423. * @param scene defines the scene where you want your assets to be loaded
  93424. * @param onSuccess is a callback called when the task is successfully executed
  93425. * @param onError is a callback called if an error occurs
  93426. */
  93427. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93428. var _this = this;
  93429. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  93430. _this.loadedMeshes = meshes;
  93431. _this.loadedParticleSystems = particleSystems;
  93432. _this.loadedSkeletons = skeletons;
  93433. onSuccess();
  93434. }, null, function (scene, message, exception) {
  93435. onError(message, exception);
  93436. });
  93437. };
  93438. return MeshAssetTask;
  93439. }(AbstractAssetTask));
  93440. BABYLON.MeshAssetTask = MeshAssetTask;
  93441. /**
  93442. * Define a task used by {BABYLON.AssetsManager} to load text content
  93443. */
  93444. var TextFileAssetTask = /** @class */ (function (_super) {
  93445. __extends(TextFileAssetTask, _super);
  93446. /**
  93447. * Creates a new TextFileAssetTask object
  93448. * @param name defines the name of the task
  93449. * @param url defines the location of the file to load
  93450. */
  93451. function TextFileAssetTask(
  93452. /**
  93453. * Defines the name of the task
  93454. */
  93455. name,
  93456. /**
  93457. * Defines the location of the file to load
  93458. */
  93459. url) {
  93460. var _this = _super.call(this, name) || this;
  93461. _this.name = name;
  93462. _this.url = url;
  93463. return _this;
  93464. }
  93465. /**
  93466. * Execute the current task
  93467. * @param scene defines the scene where you want your assets to be loaded
  93468. * @param onSuccess is a callback called when the task is successfully executed
  93469. * @param onError is a callback called if an error occurs
  93470. */
  93471. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93472. var _this = this;
  93473. scene._loadFile(this.url, function (data) {
  93474. _this.text = data;
  93475. onSuccess();
  93476. }, undefined, false, false, function (request, exception) {
  93477. if (request) {
  93478. onError(request.status + " " + request.statusText, exception);
  93479. }
  93480. });
  93481. };
  93482. return TextFileAssetTask;
  93483. }(AbstractAssetTask));
  93484. BABYLON.TextFileAssetTask = TextFileAssetTask;
  93485. /**
  93486. * Define a task used by {BABYLON.AssetsManager} to load binary data
  93487. */
  93488. var BinaryFileAssetTask = /** @class */ (function (_super) {
  93489. __extends(BinaryFileAssetTask, _super);
  93490. /**
  93491. * Creates a new BinaryFileAssetTask object
  93492. * @param name defines the name of the new task
  93493. * @param url defines the location of the file to load
  93494. */
  93495. function BinaryFileAssetTask(
  93496. /**
  93497. * Defines the name of the task
  93498. */
  93499. name,
  93500. /**
  93501. * Defines the location of the file to load
  93502. */
  93503. url) {
  93504. var _this = _super.call(this, name) || this;
  93505. _this.name = name;
  93506. _this.url = url;
  93507. return _this;
  93508. }
  93509. /**
  93510. * Execute the current task
  93511. * @param scene defines the scene where you want your assets to be loaded
  93512. * @param onSuccess is a callback called when the task is successfully executed
  93513. * @param onError is a callback called if an error occurs
  93514. */
  93515. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93516. var _this = this;
  93517. scene._loadFile(this.url, function (data) {
  93518. _this.data = data;
  93519. onSuccess();
  93520. }, undefined, true, true, function (request, exception) {
  93521. if (request) {
  93522. onError(request.status + " " + request.statusText, exception);
  93523. }
  93524. });
  93525. };
  93526. return BinaryFileAssetTask;
  93527. }(AbstractAssetTask));
  93528. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  93529. /**
  93530. * Define a task used by {BABYLON.AssetsManager} to load images
  93531. */
  93532. var ImageAssetTask = /** @class */ (function (_super) {
  93533. __extends(ImageAssetTask, _super);
  93534. /**
  93535. * Creates a new ImageAssetTask
  93536. * @param name defines the name of the task
  93537. * @param url defines the location of the image to load
  93538. */
  93539. function ImageAssetTask(
  93540. /**
  93541. * Defines the name of the task
  93542. */
  93543. name,
  93544. /**
  93545. * Defines the location of the image to load
  93546. */
  93547. url) {
  93548. var _this = _super.call(this, name) || this;
  93549. _this.name = name;
  93550. _this.url = url;
  93551. return _this;
  93552. }
  93553. /**
  93554. * Execute the current task
  93555. * @param scene defines the scene where you want your assets to be loaded
  93556. * @param onSuccess is a callback called when the task is successfully executed
  93557. * @param onError is a callback called if an error occurs
  93558. */
  93559. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93560. var _this = this;
  93561. var img = new Image();
  93562. BABYLON.Tools.SetCorsBehavior(this.url, img);
  93563. img.onload = function () {
  93564. _this.image = img;
  93565. onSuccess();
  93566. };
  93567. img.onerror = function (err) {
  93568. onError("Error loading image", err);
  93569. };
  93570. img.src = this.url;
  93571. };
  93572. return ImageAssetTask;
  93573. }(AbstractAssetTask));
  93574. BABYLON.ImageAssetTask = ImageAssetTask;
  93575. /**
  93576. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  93577. */
  93578. var TextureAssetTask = /** @class */ (function (_super) {
  93579. __extends(TextureAssetTask, _super);
  93580. /**
  93581. * Creates a new TextureAssetTask object
  93582. * @param name defines the name of the task
  93583. * @param url defines the location of the file to load
  93584. * @param noMipmap defines if mipmap should not be generated (default is false)
  93585. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93586. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93587. */
  93588. function TextureAssetTask(
  93589. /**
  93590. * Defines the name of the task
  93591. */
  93592. name,
  93593. /**
  93594. * Defines the location of the file to load
  93595. */
  93596. url,
  93597. /**
  93598. * Defines if mipmap should not be generated (default is false)
  93599. */
  93600. noMipmap,
  93601. /**
  93602. * Defines if texture must be inverted on Y axis (default is false)
  93603. */
  93604. invertY,
  93605. /**
  93606. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93607. */
  93608. samplingMode) {
  93609. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93610. var _this = _super.call(this, name) || this;
  93611. _this.name = name;
  93612. _this.url = url;
  93613. _this.noMipmap = noMipmap;
  93614. _this.invertY = invertY;
  93615. _this.samplingMode = samplingMode;
  93616. return _this;
  93617. }
  93618. /**
  93619. * Execute the current task
  93620. * @param scene defines the scene where you want your assets to be loaded
  93621. * @param onSuccess is a callback called when the task is successfully executed
  93622. * @param onError is a callback called if an error occurs
  93623. */
  93624. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93625. var onload = function () {
  93626. onSuccess();
  93627. };
  93628. var onerror = function (message, exception) {
  93629. onError(message, exception);
  93630. };
  93631. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93632. };
  93633. return TextureAssetTask;
  93634. }(AbstractAssetTask));
  93635. BABYLON.TextureAssetTask = TextureAssetTask;
  93636. /**
  93637. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93638. */
  93639. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93640. __extends(CubeTextureAssetTask, _super);
  93641. /**
  93642. * Creates a new CubeTextureAssetTask
  93643. * @param name defines the name of the task
  93644. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93645. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93646. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93647. * @param files defines the explicit list of files (undefined by default)
  93648. */
  93649. function CubeTextureAssetTask(
  93650. /**
  93651. * Defines the name of the task
  93652. */
  93653. name,
  93654. /**
  93655. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93656. */
  93657. url,
  93658. /**
  93659. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93660. */
  93661. extensions,
  93662. /**
  93663. * Defines if mipmaps should not be generated (default is false)
  93664. */
  93665. noMipmap,
  93666. /**
  93667. * Defines the explicit list of files (undefined by default)
  93668. */
  93669. files) {
  93670. var _this = _super.call(this, name) || this;
  93671. _this.name = name;
  93672. _this.url = url;
  93673. _this.extensions = extensions;
  93674. _this.noMipmap = noMipmap;
  93675. _this.files = files;
  93676. return _this;
  93677. }
  93678. /**
  93679. * Execute the current task
  93680. * @param scene defines the scene where you want your assets to be loaded
  93681. * @param onSuccess is a callback called when the task is successfully executed
  93682. * @param onError is a callback called if an error occurs
  93683. */
  93684. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93685. var onload = function () {
  93686. onSuccess();
  93687. };
  93688. var onerror = function (message, exception) {
  93689. onError(message, exception);
  93690. };
  93691. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93692. };
  93693. return CubeTextureAssetTask;
  93694. }(AbstractAssetTask));
  93695. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93696. /**
  93697. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93698. */
  93699. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93700. __extends(HDRCubeTextureAssetTask, _super);
  93701. /**
  93702. * Creates a new HDRCubeTextureAssetTask object
  93703. * @param name defines the name of the task
  93704. * @param url defines the location of the file to load
  93705. * @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.
  93706. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93707. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93708. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  93709. * @param reserved Internal use only
  93710. */
  93711. function HDRCubeTextureAssetTask(
  93712. /**
  93713. * Defines the name of the task
  93714. */
  93715. name,
  93716. /**
  93717. * Defines the location of the file to load
  93718. */
  93719. url,
  93720. /**
  93721. * Defines the desired size (the more it increases the longer the generation will be)
  93722. */
  93723. size,
  93724. /**
  93725. * Defines if mipmaps should not be generated (default is false)
  93726. */
  93727. noMipmap,
  93728. /**
  93729. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93730. */
  93731. generateHarmonics,
  93732. /**
  93733. * 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)
  93734. */
  93735. gammaSpace,
  93736. /**
  93737. * Internal Use Only
  93738. */
  93739. reserved) {
  93740. if (noMipmap === void 0) { noMipmap = false; }
  93741. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93742. if (gammaSpace === void 0) { gammaSpace = false; }
  93743. if (reserved === void 0) { reserved = false; }
  93744. var _this = _super.call(this, name) || this;
  93745. _this.name = name;
  93746. _this.url = url;
  93747. _this.size = size;
  93748. _this.noMipmap = noMipmap;
  93749. _this.generateHarmonics = generateHarmonics;
  93750. _this.gammaSpace = gammaSpace;
  93751. _this.reserved = reserved;
  93752. return _this;
  93753. }
  93754. /**
  93755. * Execute the current task
  93756. * @param scene defines the scene where you want your assets to be loaded
  93757. * @param onSuccess is a callback called when the task is successfully executed
  93758. * @param onError is a callback called if an error occurs
  93759. */
  93760. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93761. var onload = function () {
  93762. onSuccess();
  93763. };
  93764. var onerror = function (message, exception) {
  93765. onError(message, exception);
  93766. };
  93767. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93768. };
  93769. return HDRCubeTextureAssetTask;
  93770. }(AbstractAssetTask));
  93771. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93772. /**
  93773. * This class can be used to easily import assets into a scene
  93774. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93775. */
  93776. var AssetsManager = /** @class */ (function () {
  93777. /**
  93778. * Creates a new AssetsManager
  93779. * @param scene defines the scene to work on
  93780. */
  93781. function AssetsManager(scene) {
  93782. this._isLoading = false;
  93783. this._tasks = new Array();
  93784. this._waitingTasksCount = 0;
  93785. this._totalTasksCount = 0;
  93786. /**
  93787. * Observable called when all tasks are processed
  93788. */
  93789. this.onTaskSuccessObservable = new BABYLON.Observable();
  93790. /**
  93791. * Observable called when a task had an error
  93792. */
  93793. this.onTaskErrorObservable = new BABYLON.Observable();
  93794. /**
  93795. * Observable called when a task is successful
  93796. */
  93797. this.onTasksDoneObservable = new BABYLON.Observable();
  93798. /**
  93799. * Observable called when a task is done (whatever the result is)
  93800. */
  93801. this.onProgressObservable = new BABYLON.Observable();
  93802. /**
  93803. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93804. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93805. */
  93806. this.useDefaultLoadingScreen = true;
  93807. this._scene = scene;
  93808. }
  93809. /**
  93810. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93811. * @param taskName defines the name of the new task
  93812. * @param meshesNames defines the name of meshes to load
  93813. * @param rootUrl defines the root url to use to locate files
  93814. * @param sceneFilename defines the filename of the scene file
  93815. * @returns a new {BABYLON.MeshAssetTask} object
  93816. */
  93817. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93818. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93819. this._tasks.push(task);
  93820. return task;
  93821. };
  93822. /**
  93823. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93824. * @param taskName defines the name of the new task
  93825. * @param url defines the url of the file to load
  93826. * @returns a new {BABYLON.TextFileAssetTask} object
  93827. */
  93828. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93829. var task = new TextFileAssetTask(taskName, url);
  93830. this._tasks.push(task);
  93831. return task;
  93832. };
  93833. /**
  93834. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93835. * @param taskName defines the name of the new task
  93836. * @param url defines the url of the file to load
  93837. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93838. */
  93839. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93840. var task = new BinaryFileAssetTask(taskName, url);
  93841. this._tasks.push(task);
  93842. return task;
  93843. };
  93844. /**
  93845. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93846. * @param taskName defines the name of the new task
  93847. * @param url defines the url of the file to load
  93848. * @returns a new {BABYLON.ImageAssetTask} object
  93849. */
  93850. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93851. var task = new ImageAssetTask(taskName, url);
  93852. this._tasks.push(task);
  93853. return task;
  93854. };
  93855. /**
  93856. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93857. * @param taskName defines the name of the new task
  93858. * @param url defines the url of the file to load
  93859. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93860. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93861. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93862. * @returns a new {BABYLON.TextureAssetTask} object
  93863. */
  93864. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93865. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93866. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93867. this._tasks.push(task);
  93868. return task;
  93869. };
  93870. /**
  93871. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93872. * @param taskName defines the name of the new task
  93873. * @param url defines the url of the file to load
  93874. * @param extensions defines the extension to use to load the cube map (can be null)
  93875. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93876. * @param files defines the list of files to load (can be null)
  93877. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93878. */
  93879. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93880. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93881. this._tasks.push(task);
  93882. return task;
  93883. };
  93884. /**
  93885. *
  93886. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93887. * @param taskName defines the name of the new task
  93888. * @param url defines the url of the file to load
  93889. * @param size defines the size you want for the cubemap (can be null)
  93890. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93891. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93892. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  93893. * @param reserved Internal use only
  93894. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93895. */
  93896. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93897. if (noMipmap === void 0) { noMipmap = false; }
  93898. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93899. if (gammaSpace === void 0) { gammaSpace = false; }
  93900. if (reserved === void 0) { reserved = false; }
  93901. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93902. this._tasks.push(task);
  93903. return task;
  93904. };
  93905. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93906. this._waitingTasksCount--;
  93907. try {
  93908. if (this.onProgress) {
  93909. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93910. }
  93911. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93912. }
  93913. catch (e) {
  93914. BABYLON.Tools.Error("Error running progress callbacks.");
  93915. console.log(e);
  93916. }
  93917. if (this._waitingTasksCount === 0) {
  93918. try {
  93919. if (this.onFinish) {
  93920. this.onFinish(this._tasks);
  93921. }
  93922. // Let's remove successfull tasks
  93923. var currentTasks = this._tasks.slice();
  93924. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  93925. var task = currentTasks_1[_i];
  93926. if (task.taskState === AssetTaskState.DONE) {
  93927. var index = this._tasks.indexOf(task);
  93928. if (index > -1) {
  93929. this._tasks.splice(index, 1);
  93930. }
  93931. }
  93932. }
  93933. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93934. }
  93935. catch (e) {
  93936. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93937. console.log(e);
  93938. }
  93939. this._isLoading = false;
  93940. this._scene.getEngine().hideLoadingUI();
  93941. }
  93942. };
  93943. AssetsManager.prototype._runTask = function (task) {
  93944. var _this = this;
  93945. var done = function () {
  93946. try {
  93947. if (_this.onTaskSuccess) {
  93948. _this.onTaskSuccess(task);
  93949. }
  93950. _this.onTaskSuccessObservable.notifyObservers(task);
  93951. _this._decreaseWaitingTasksCount(task);
  93952. }
  93953. catch (e) {
  93954. error("Error executing task success callbacks", e);
  93955. }
  93956. };
  93957. var error = function (message, exception) {
  93958. task._setErrorObject(message, exception);
  93959. if (_this.onTaskError) {
  93960. _this.onTaskError(task);
  93961. }
  93962. _this.onTaskErrorObservable.notifyObservers(task);
  93963. _this._decreaseWaitingTasksCount(task);
  93964. };
  93965. task.run(this._scene, done, error);
  93966. };
  93967. /**
  93968. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93969. * @return the current instance of the {BABYLON.AssetsManager}
  93970. */
  93971. AssetsManager.prototype.reset = function () {
  93972. this._isLoading = false;
  93973. this._tasks = new Array();
  93974. return this;
  93975. };
  93976. /**
  93977. * Start the loading process
  93978. * @return the current instance of the {BABYLON.AssetsManager}
  93979. */
  93980. AssetsManager.prototype.load = function () {
  93981. if (this._isLoading) {
  93982. return this;
  93983. }
  93984. this._isLoading = true;
  93985. this._waitingTasksCount = this._tasks.length;
  93986. this._totalTasksCount = this._tasks.length;
  93987. if (this._waitingTasksCount === 0) {
  93988. this._isLoading = false;
  93989. if (this.onFinish) {
  93990. this.onFinish(this._tasks);
  93991. }
  93992. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93993. return this;
  93994. }
  93995. if (this.useDefaultLoadingScreen) {
  93996. this._scene.getEngine().displayLoadingUI();
  93997. }
  93998. for (var index = 0; index < this._tasks.length; index++) {
  93999. var task = this._tasks[index];
  94000. this._runTask(task);
  94001. }
  94002. return this;
  94003. };
  94004. return AssetsManager;
  94005. }());
  94006. BABYLON.AssetsManager = AssetsManager;
  94007. })(BABYLON || (BABYLON = {}));
  94008. //# sourceMappingURL=babylon.assetsManager.js.map
  94009. var BABYLON;
  94010. (function (BABYLON) {
  94011. var serializedGeometries = [];
  94012. var serializeGeometry = function (geometry, serializationGeometries) {
  94013. if (serializedGeometries[geometry.id]) {
  94014. return;
  94015. }
  94016. if (geometry.doNotSerialize) {
  94017. return;
  94018. }
  94019. if (geometry instanceof BABYLON.BoxGeometry) {
  94020. serializationGeometries.boxes.push(geometry.serialize());
  94021. }
  94022. else if (geometry instanceof BABYLON.SphereGeometry) {
  94023. serializationGeometries.spheres.push(geometry.serialize());
  94024. }
  94025. else if (geometry instanceof BABYLON.CylinderGeometry) {
  94026. serializationGeometries.cylinders.push(geometry.serialize());
  94027. }
  94028. else if (geometry instanceof BABYLON.TorusGeometry) {
  94029. serializationGeometries.toruses.push(geometry.serialize());
  94030. }
  94031. else if (geometry instanceof BABYLON.GroundGeometry) {
  94032. serializationGeometries.grounds.push(geometry.serialize());
  94033. }
  94034. else if (geometry instanceof BABYLON.Plane) {
  94035. serializationGeometries.planes.push(geometry.serialize());
  94036. }
  94037. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  94038. serializationGeometries.torusKnots.push(geometry.serialize());
  94039. }
  94040. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  94041. throw new Error("Unknown primitive type");
  94042. }
  94043. else {
  94044. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  94045. }
  94046. serializedGeometries[geometry.id] = true;
  94047. };
  94048. var serializeMesh = function (mesh, serializationScene) {
  94049. var serializationObject = {};
  94050. // Geometry
  94051. var geometry = mesh._geometry;
  94052. if (geometry) {
  94053. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  94054. // 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
  94055. serializeGeometry(geometry, serializationScene.geometries);
  94056. }
  94057. }
  94058. // Custom
  94059. if (mesh.serialize) {
  94060. mesh.serialize(serializationObject);
  94061. }
  94062. return serializationObject;
  94063. };
  94064. var finalizeSingleMesh = function (mesh, serializationObject) {
  94065. //only works if the mesh is already loaded
  94066. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  94067. //serialize material
  94068. if (mesh.material) {
  94069. if (mesh.material instanceof BABYLON.StandardMaterial) {
  94070. serializationObject.materials = serializationObject.materials || [];
  94071. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  94072. serializationObject.materials.push(mesh.material.serialize());
  94073. }
  94074. }
  94075. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  94076. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  94077. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  94078. serializationObject.multiMaterials.push(mesh.material.serialize());
  94079. }
  94080. }
  94081. }
  94082. //serialize geometry
  94083. var geometry = mesh._geometry;
  94084. if (geometry) {
  94085. if (!serializationObject.geometries) {
  94086. serializationObject.geometries = {};
  94087. serializationObject.geometries.boxes = [];
  94088. serializationObject.geometries.spheres = [];
  94089. serializationObject.geometries.cylinders = [];
  94090. serializationObject.geometries.toruses = [];
  94091. serializationObject.geometries.grounds = [];
  94092. serializationObject.geometries.planes = [];
  94093. serializationObject.geometries.torusKnots = [];
  94094. serializationObject.geometries.vertexData = [];
  94095. }
  94096. serializeGeometry(geometry, serializationObject.geometries);
  94097. }
  94098. // Skeletons
  94099. if (mesh.skeleton) {
  94100. serializationObject.skeletons = serializationObject.skeletons || [];
  94101. serializationObject.skeletons.push(mesh.skeleton.serialize());
  94102. }
  94103. //serialize the actual mesh
  94104. serializationObject.meshes = serializationObject.meshes || [];
  94105. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  94106. }
  94107. };
  94108. var SceneSerializer = /** @class */ (function () {
  94109. function SceneSerializer() {
  94110. }
  94111. SceneSerializer.ClearCache = function () {
  94112. serializedGeometries = [];
  94113. };
  94114. SceneSerializer.Serialize = function (scene) {
  94115. var serializationObject = {};
  94116. SceneSerializer.ClearCache();
  94117. // Scene
  94118. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  94119. serializationObject.autoClear = scene.autoClear;
  94120. serializationObject.clearColor = scene.clearColor.asArray();
  94121. serializationObject.ambientColor = scene.ambientColor.asArray();
  94122. serializationObject.gravity = scene.gravity.asArray();
  94123. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  94124. serializationObject.workerCollisions = scene.workerCollisions;
  94125. // Fog
  94126. if (scene.fogMode && scene.fogMode !== 0) {
  94127. serializationObject.fogMode = scene.fogMode;
  94128. serializationObject.fogColor = scene.fogColor.asArray();
  94129. serializationObject.fogStart = scene.fogStart;
  94130. serializationObject.fogEnd = scene.fogEnd;
  94131. serializationObject.fogDensity = scene.fogDensity;
  94132. }
  94133. //Physics
  94134. if (scene.isPhysicsEnabled()) {
  94135. var physicEngine = scene.getPhysicsEngine();
  94136. if (physicEngine) {
  94137. serializationObject.physicsEnabled = true;
  94138. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  94139. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  94140. }
  94141. }
  94142. // Metadata
  94143. if (scene.metadata) {
  94144. serializationObject.metadata = scene.metadata;
  94145. }
  94146. // Morph targets
  94147. serializationObject.morphTargetManagers = [];
  94148. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  94149. var abstractMesh = _a[_i];
  94150. var manager = abstractMesh.morphTargetManager;
  94151. if (manager) {
  94152. serializationObject.morphTargetManagers.push(manager.serialize());
  94153. }
  94154. }
  94155. // Lights
  94156. serializationObject.lights = [];
  94157. var index;
  94158. var light;
  94159. for (index = 0; index < scene.lights.length; index++) {
  94160. light = scene.lights[index];
  94161. if (!light.doNotSerialize) {
  94162. serializationObject.lights.push(light.serialize());
  94163. }
  94164. }
  94165. // Cameras
  94166. serializationObject.cameras = [];
  94167. for (index = 0; index < scene.cameras.length; index++) {
  94168. var camera = scene.cameras[index];
  94169. if (!camera.doNotSerialize) {
  94170. serializationObject.cameras.push(camera.serialize());
  94171. }
  94172. }
  94173. if (scene.activeCamera) {
  94174. serializationObject.activeCameraID = scene.activeCamera.id;
  94175. }
  94176. // Animations
  94177. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  94178. // Materials
  94179. serializationObject.materials = [];
  94180. serializationObject.multiMaterials = [];
  94181. var material;
  94182. for (index = 0; index < scene.materials.length; index++) {
  94183. material = scene.materials[index];
  94184. if (!material.doNotSerialize) {
  94185. serializationObject.materials.push(material.serialize());
  94186. }
  94187. }
  94188. // MultiMaterials
  94189. serializationObject.multiMaterials = [];
  94190. for (index = 0; index < scene.multiMaterials.length; index++) {
  94191. var multiMaterial = scene.multiMaterials[index];
  94192. serializationObject.multiMaterials.push(multiMaterial.serialize());
  94193. }
  94194. // Environment texture
  94195. if (scene.environmentTexture) {
  94196. serializationObject.environmentTexture = scene.environmentTexture.name;
  94197. }
  94198. // Skeletons
  94199. serializationObject.skeletons = [];
  94200. for (index = 0; index < scene.skeletons.length; index++) {
  94201. var skeleton = scene.skeletons[index];
  94202. if (!skeleton.doNotSerialize) {
  94203. serializationObject.skeletons.push(skeleton.serialize());
  94204. }
  94205. }
  94206. // Transform nodes
  94207. serializationObject.transformNodes = [];
  94208. for (index = 0; index < scene.transformNodes.length; index++) {
  94209. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  94210. }
  94211. // Geometries
  94212. serializationObject.geometries = {};
  94213. serializationObject.geometries.boxes = [];
  94214. serializationObject.geometries.spheres = [];
  94215. serializationObject.geometries.cylinders = [];
  94216. serializationObject.geometries.toruses = [];
  94217. serializationObject.geometries.grounds = [];
  94218. serializationObject.geometries.planes = [];
  94219. serializationObject.geometries.torusKnots = [];
  94220. serializationObject.geometries.vertexData = [];
  94221. serializedGeometries = [];
  94222. var geometries = scene.getGeometries();
  94223. for (index = 0; index < geometries.length; index++) {
  94224. var geometry = geometries[index];
  94225. if (geometry.isReady()) {
  94226. serializeGeometry(geometry, serializationObject.geometries);
  94227. }
  94228. }
  94229. // Meshes
  94230. serializationObject.meshes = [];
  94231. for (index = 0; index < scene.meshes.length; index++) {
  94232. var abstractMesh = scene.meshes[index];
  94233. if (abstractMesh instanceof BABYLON.Mesh) {
  94234. var mesh = abstractMesh;
  94235. if (!mesh.doNotSerialize) {
  94236. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  94237. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  94238. }
  94239. }
  94240. }
  94241. }
  94242. // Particles Systems
  94243. serializationObject.particleSystems = [];
  94244. for (index = 0; index < scene.particleSystems.length; index++) {
  94245. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  94246. }
  94247. // Lens flares
  94248. serializationObject.lensFlareSystems = [];
  94249. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  94250. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  94251. }
  94252. // Shadows
  94253. serializationObject.shadowGenerators = [];
  94254. for (index = 0; index < scene.lights.length; index++) {
  94255. light = scene.lights[index];
  94256. var shadowGenerator = light.getShadowGenerator();
  94257. if (shadowGenerator) {
  94258. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  94259. }
  94260. }
  94261. // Action Manager
  94262. if (scene.actionManager) {
  94263. serializationObject.actions = scene.actionManager.serialize("scene");
  94264. }
  94265. // Audio
  94266. serializationObject.sounds = [];
  94267. for (index = 0; index < scene.soundTracks.length; index++) {
  94268. var soundtrack = scene.soundTracks[index];
  94269. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  94270. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  94271. }
  94272. }
  94273. // Effect layers
  94274. serializationObject.effectLayers = [];
  94275. for (index = 0; index < scene.effectLayers.length; index++) {
  94276. var layer = scene.effectLayers[index];
  94277. if (layer.serialize) {
  94278. serializationObject.effectLayers.push(layer.serialize());
  94279. }
  94280. }
  94281. return serializationObject;
  94282. };
  94283. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  94284. if (withParents === void 0) { withParents = false; }
  94285. if (withChildren === void 0) { withChildren = false; }
  94286. var serializationObject = {};
  94287. SceneSerializer.ClearCache();
  94288. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  94289. if (withParents || withChildren) {
  94290. //deliberate for loop! not for each, appended should be processed as well.
  94291. for (var i = 0; i < toSerialize.length; ++i) {
  94292. if (withChildren) {
  94293. toSerialize[i].getDescendants().forEach(function (node) {
  94294. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  94295. toSerialize.push(node);
  94296. }
  94297. });
  94298. }
  94299. //make sure the array doesn't contain the object already
  94300. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  94301. toSerialize.push(toSerialize[i].parent);
  94302. }
  94303. }
  94304. }
  94305. toSerialize.forEach(function (mesh) {
  94306. finalizeSingleMesh(mesh, serializationObject);
  94307. });
  94308. return serializationObject;
  94309. };
  94310. return SceneSerializer;
  94311. }());
  94312. BABYLON.SceneSerializer = SceneSerializer;
  94313. })(BABYLON || (BABYLON = {}));
  94314. //# sourceMappingURL=babylon.sceneSerializer.js.map
  94315. var BABYLON;
  94316. (function (BABYLON) {
  94317. var ReflectionProbe = /** @class */ (function () {
  94318. function ReflectionProbe(name, size, scene, generateMipMaps) {
  94319. if (generateMipMaps === void 0) { generateMipMaps = true; }
  94320. var _this = this;
  94321. this.name = name;
  94322. this._viewMatrix = BABYLON.Matrix.Identity();
  94323. this._target = BABYLON.Vector3.Zero();
  94324. this._add = BABYLON.Vector3.Zero();
  94325. this._invertYAxis = false;
  94326. this.position = BABYLON.Vector3.Zero();
  94327. this._scene = scene;
  94328. this._scene.reflectionProbes.push(this);
  94329. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  94330. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  94331. switch (faceIndex) {
  94332. case 0:
  94333. _this._add.copyFromFloats(1, 0, 0);
  94334. break;
  94335. case 1:
  94336. _this._add.copyFromFloats(-1, 0, 0);
  94337. break;
  94338. case 2:
  94339. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  94340. break;
  94341. case 3:
  94342. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  94343. break;
  94344. case 4:
  94345. _this._add.copyFromFloats(0, 0, 1);
  94346. break;
  94347. case 5:
  94348. _this._add.copyFromFloats(0, 0, -1);
  94349. break;
  94350. }
  94351. if (_this._attachedMesh) {
  94352. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  94353. }
  94354. _this.position.addToRef(_this._add, _this._target);
  94355. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  94356. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  94357. scene._forcedViewPosition = _this.position;
  94358. });
  94359. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  94360. scene._forcedViewPosition = null;
  94361. scene.updateTransformMatrix(true);
  94362. });
  94363. if (scene.activeCamera) {
  94364. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  94365. }
  94366. }
  94367. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  94368. get: function () {
  94369. return this._renderTargetTexture.samples;
  94370. },
  94371. set: function (value) {
  94372. this._renderTargetTexture.samples = value;
  94373. },
  94374. enumerable: true,
  94375. configurable: true
  94376. });
  94377. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  94378. get: function () {
  94379. return this._renderTargetTexture.refreshRate;
  94380. },
  94381. set: function (value) {
  94382. this._renderTargetTexture.refreshRate = value;
  94383. },
  94384. enumerable: true,
  94385. configurable: true
  94386. });
  94387. ReflectionProbe.prototype.getScene = function () {
  94388. return this._scene;
  94389. };
  94390. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  94391. get: function () {
  94392. return this._renderTargetTexture;
  94393. },
  94394. enumerable: true,
  94395. configurable: true
  94396. });
  94397. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  94398. get: function () {
  94399. return this._renderTargetTexture.renderList;
  94400. },
  94401. enumerable: true,
  94402. configurable: true
  94403. });
  94404. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  94405. this._attachedMesh = mesh;
  94406. };
  94407. /**
  94408. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  94409. *
  94410. * @param renderingGroupId The rendering group id corresponding to its index
  94411. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  94412. */
  94413. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  94414. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  94415. };
  94416. ReflectionProbe.prototype.dispose = function () {
  94417. var index = this._scene.reflectionProbes.indexOf(this);
  94418. if (index !== -1) {
  94419. // Remove from the scene if found
  94420. this._scene.reflectionProbes.splice(index, 1);
  94421. }
  94422. if (this._renderTargetTexture) {
  94423. this._renderTargetTexture.dispose();
  94424. this._renderTargetTexture = null;
  94425. }
  94426. };
  94427. return ReflectionProbe;
  94428. }());
  94429. BABYLON.ReflectionProbe = ReflectionProbe;
  94430. })(BABYLON || (BABYLON = {}));
  94431. //# sourceMappingURL=babylon.reflectionProbe.js.map
  94432. var BABYLON;
  94433. (function (BABYLON) {
  94434. var Layer = /** @class */ (function () {
  94435. function Layer(name, imgUrl, scene, isBackground, color) {
  94436. this.name = name;
  94437. this.scale = new BABYLON.Vector2(1, 1);
  94438. this.offset = new BABYLON.Vector2(0, 0);
  94439. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  94440. this.layerMask = 0x0FFFFFFF;
  94441. this._vertexBuffers = {};
  94442. // Events
  94443. /**
  94444. * An event triggered when the layer is disposed.
  94445. */
  94446. this.onDisposeObservable = new BABYLON.Observable();
  94447. /**
  94448. * An event triggered before rendering the scene
  94449. */
  94450. this.onBeforeRenderObservable = new BABYLON.Observable();
  94451. /**
  94452. * An event triggered after rendering the scene
  94453. */
  94454. this.onAfterRenderObservable = new BABYLON.Observable();
  94455. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  94456. this.isBackground = isBackground === undefined ? true : isBackground;
  94457. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  94458. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  94459. this._scene.layers.push(this);
  94460. var engine = this._scene.getEngine();
  94461. // VBO
  94462. var vertices = [];
  94463. vertices.push(1, 1);
  94464. vertices.push(-1, 1);
  94465. vertices.push(-1, -1);
  94466. vertices.push(1, -1);
  94467. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94468. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94469. this._createIndexBuffer();
  94470. // Effects
  94471. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  94472. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  94473. }
  94474. Object.defineProperty(Layer.prototype, "onDispose", {
  94475. set: function (callback) {
  94476. if (this._onDisposeObserver) {
  94477. this.onDisposeObservable.remove(this._onDisposeObserver);
  94478. }
  94479. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  94480. },
  94481. enumerable: true,
  94482. configurable: true
  94483. });
  94484. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  94485. set: function (callback) {
  94486. if (this._onBeforeRenderObserver) {
  94487. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  94488. }
  94489. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  94490. },
  94491. enumerable: true,
  94492. configurable: true
  94493. });
  94494. Object.defineProperty(Layer.prototype, "onAfterRender", {
  94495. set: function (callback) {
  94496. if (this._onAfterRenderObserver) {
  94497. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94498. }
  94499. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  94500. },
  94501. enumerable: true,
  94502. configurable: true
  94503. });
  94504. Layer.prototype._createIndexBuffer = function () {
  94505. var engine = this._scene.getEngine();
  94506. // Indices
  94507. var indices = [];
  94508. indices.push(0);
  94509. indices.push(1);
  94510. indices.push(2);
  94511. indices.push(0);
  94512. indices.push(2);
  94513. indices.push(3);
  94514. this._indexBuffer = engine.createIndexBuffer(indices);
  94515. };
  94516. Layer.prototype._rebuild = function () {
  94517. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94518. if (vb) {
  94519. vb._rebuild();
  94520. }
  94521. this._createIndexBuffer();
  94522. };
  94523. Layer.prototype.render = function () {
  94524. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  94525. // Check
  94526. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  94527. return;
  94528. var engine = this._scene.getEngine();
  94529. this.onBeforeRenderObservable.notifyObservers(this);
  94530. // Render
  94531. engine.enableEffect(currentEffect);
  94532. engine.setState(false);
  94533. // Texture
  94534. currentEffect.setTexture("textureSampler", this.texture);
  94535. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  94536. // Color
  94537. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  94538. // Scale / offset
  94539. currentEffect.setVector2("offset", this.offset);
  94540. currentEffect.setVector2("scale", this.scale);
  94541. // VBOs
  94542. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94543. // Draw order
  94544. if (!this.alphaTest) {
  94545. engine.setAlphaMode(this.alphaBlendingMode);
  94546. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94547. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94548. }
  94549. else {
  94550. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94551. }
  94552. this.onAfterRenderObservable.notifyObservers(this);
  94553. };
  94554. Layer.prototype.dispose = function () {
  94555. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94556. if (vertexBuffer) {
  94557. vertexBuffer.dispose();
  94558. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94559. }
  94560. if (this._indexBuffer) {
  94561. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94562. this._indexBuffer = null;
  94563. }
  94564. if (this.texture) {
  94565. this.texture.dispose();
  94566. this.texture = null;
  94567. }
  94568. // Remove from scene
  94569. var index = this._scene.layers.indexOf(this);
  94570. this._scene.layers.splice(index, 1);
  94571. // Callback
  94572. this.onDisposeObservable.notifyObservers(this);
  94573. this.onDisposeObservable.clear();
  94574. this.onAfterRenderObservable.clear();
  94575. this.onBeforeRenderObservable.clear();
  94576. };
  94577. return Layer;
  94578. }());
  94579. BABYLON.Layer = Layer;
  94580. })(BABYLON || (BABYLON = {}));
  94581. //# sourceMappingURL=babylon.layer.js.map
  94582. var BABYLON;
  94583. (function (BABYLON) {
  94584. var TextureTools = /** @class */ (function () {
  94585. function TextureTools() {
  94586. }
  94587. /**
  94588. * Uses the GPU to create a copy texture rescaled at a given size
  94589. * @param texture Texture to copy from
  94590. * @param width Desired width
  94591. * @param height Desired height
  94592. * @return Generated texture
  94593. */
  94594. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94595. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94596. var scene = texture.getScene();
  94597. var engine = scene.getEngine();
  94598. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94599. rtt.wrapU = texture.wrapU;
  94600. rtt.wrapV = texture.wrapV;
  94601. rtt.uOffset = texture.uOffset;
  94602. rtt.vOffset = texture.vOffset;
  94603. rtt.uScale = texture.uScale;
  94604. rtt.vScale = texture.vScale;
  94605. rtt.uAng = texture.uAng;
  94606. rtt.vAng = texture.vAng;
  94607. rtt.wAng = texture.wAng;
  94608. rtt.coordinatesIndex = texture.coordinatesIndex;
  94609. rtt.level = texture.level;
  94610. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94611. rtt._texture.isReady = false;
  94612. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94613. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94614. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94615. passPostProcess.getEffect().executeWhenCompiled(function () {
  94616. passPostProcess.onApply = function (effect) {
  94617. effect.setTexture("textureSampler", texture);
  94618. };
  94619. var internalTexture = rtt.getInternalTexture();
  94620. if (internalTexture) {
  94621. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94622. engine.unBindFramebuffer(internalTexture);
  94623. rtt.disposeFramebufferObjects();
  94624. passPostProcess.dispose();
  94625. internalTexture.isReady = true;
  94626. }
  94627. });
  94628. return rtt;
  94629. };
  94630. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94631. if (!scene._environmentBRDFTexture) {
  94632. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94633. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94634. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94635. scene._environmentBRDFTexture = texture;
  94636. }
  94637. return scene._environmentBRDFTexture;
  94638. };
  94639. 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=";
  94640. return TextureTools;
  94641. }());
  94642. BABYLON.TextureTools = TextureTools;
  94643. })(BABYLON || (BABYLON = {}));
  94644. //# sourceMappingURL=babylon.textureTools.js.map
  94645. var BABYLON;
  94646. (function (BABYLON) {
  94647. var FramingBehavior = /** @class */ (function () {
  94648. function FramingBehavior() {
  94649. this._mode = FramingBehavior.FitFrustumSidesMode;
  94650. this._radiusScale = 1.0;
  94651. this._positionScale = 0.5;
  94652. this._defaultElevation = 0.3;
  94653. this._elevationReturnTime = 1500;
  94654. this._elevationReturnWaitTime = 1000;
  94655. this._zoomStopsAnimation = false;
  94656. this._framingTime = 1500;
  94657. this._isPointerDown = false;
  94658. this._lastInteractionTime = -Infinity;
  94659. // Framing control
  94660. this._animatables = new Array();
  94661. this._betaIsAnimating = false;
  94662. }
  94663. Object.defineProperty(FramingBehavior.prototype, "name", {
  94664. get: function () {
  94665. return "Framing";
  94666. },
  94667. enumerable: true,
  94668. configurable: true
  94669. });
  94670. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94671. /**
  94672. * Gets current mode used by the behavior.
  94673. */
  94674. get: function () {
  94675. return this._mode;
  94676. },
  94677. /**
  94678. * Sets the current mode used by the behavior
  94679. */
  94680. set: function (mode) {
  94681. this._mode = mode;
  94682. },
  94683. enumerable: true,
  94684. configurable: true
  94685. });
  94686. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94687. /**
  94688. * Gets the scale applied to the radius
  94689. */
  94690. get: function () {
  94691. return this._radiusScale;
  94692. },
  94693. /**
  94694. * Sets the scale applied to the radius (1 by default)
  94695. */
  94696. set: function (radius) {
  94697. this._radiusScale = radius;
  94698. },
  94699. enumerable: true,
  94700. configurable: true
  94701. });
  94702. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94703. /**
  94704. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94705. */
  94706. get: function () {
  94707. return this._positionScale;
  94708. },
  94709. /**
  94710. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94711. */
  94712. set: function (scale) {
  94713. this._positionScale = scale;
  94714. },
  94715. enumerable: true,
  94716. configurable: true
  94717. });
  94718. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94719. /**
  94720. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94721. * behaviour is triggered, in radians.
  94722. */
  94723. get: function () {
  94724. return this._defaultElevation;
  94725. },
  94726. /**
  94727. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94728. * behaviour is triggered, in radians.
  94729. */
  94730. set: function (elevation) {
  94731. this._defaultElevation = elevation;
  94732. },
  94733. enumerable: true,
  94734. configurable: true
  94735. });
  94736. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94737. /**
  94738. * Gets the time (in milliseconds) taken to return to the default beta position.
  94739. * Negative value indicates camera should not return to default.
  94740. */
  94741. get: function () {
  94742. return this._elevationReturnTime;
  94743. },
  94744. /**
  94745. * Sets the time (in milliseconds) taken to return to the default beta position.
  94746. * Negative value indicates camera should not return to default.
  94747. */
  94748. set: function (speed) {
  94749. this._elevationReturnTime = speed;
  94750. },
  94751. enumerable: true,
  94752. configurable: true
  94753. });
  94754. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94755. /**
  94756. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94757. */
  94758. get: function () {
  94759. return this._elevationReturnWaitTime;
  94760. },
  94761. /**
  94762. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94763. */
  94764. set: function (time) {
  94765. this._elevationReturnWaitTime = time;
  94766. },
  94767. enumerable: true,
  94768. configurable: true
  94769. });
  94770. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94771. /**
  94772. * Gets the flag that indicates if user zooming should stop animation.
  94773. */
  94774. get: function () {
  94775. return this._zoomStopsAnimation;
  94776. },
  94777. /**
  94778. * Sets the flag that indicates if user zooming should stop animation.
  94779. */
  94780. set: function (flag) {
  94781. this._zoomStopsAnimation = flag;
  94782. },
  94783. enumerable: true,
  94784. configurable: true
  94785. });
  94786. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94787. /**
  94788. * Gets the transition time when framing the mesh, in milliseconds
  94789. */
  94790. get: function () {
  94791. return this._framingTime;
  94792. },
  94793. /**
  94794. * Sets the transition time when framing the mesh, in milliseconds
  94795. */
  94796. set: function (time) {
  94797. this._framingTime = time;
  94798. },
  94799. enumerable: true,
  94800. configurable: true
  94801. });
  94802. FramingBehavior.prototype.init = function () {
  94803. // Do notihng
  94804. };
  94805. FramingBehavior.prototype.attach = function (camera) {
  94806. var _this = this;
  94807. this._attachedCamera = camera;
  94808. var scene = this._attachedCamera.getScene();
  94809. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94810. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94811. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94812. _this._isPointerDown = true;
  94813. return;
  94814. }
  94815. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94816. _this._isPointerDown = false;
  94817. }
  94818. });
  94819. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94820. if (mesh) {
  94821. _this.zoomOnMesh(mesh);
  94822. }
  94823. });
  94824. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94825. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94826. _this._applyUserInteraction();
  94827. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94828. // back to the default position after a given timeout
  94829. _this._maintainCameraAboveGround();
  94830. });
  94831. };
  94832. FramingBehavior.prototype.detach = function () {
  94833. if (!this._attachedCamera) {
  94834. return;
  94835. }
  94836. var scene = this._attachedCamera.getScene();
  94837. if (this._onPrePointerObservableObserver) {
  94838. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94839. }
  94840. if (this._onAfterCheckInputsObserver) {
  94841. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94842. }
  94843. if (this._onMeshTargetChangedObserver) {
  94844. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94845. }
  94846. this._attachedCamera = null;
  94847. };
  94848. /**
  94849. * Targets the given mesh and updates zoom level accordingly.
  94850. * @param mesh The mesh to target.
  94851. * @param radius Optional. If a cached radius position already exists, overrides default.
  94852. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94853. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94854. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94855. */
  94856. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94857. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94858. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94859. mesh.computeWorldMatrix(true);
  94860. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94861. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94862. };
  94863. /**
  94864. * Targets the given mesh with its children and updates zoom level accordingly.
  94865. * @param mesh The mesh to target.
  94866. * @param radius Optional. If a cached radius position already exists, overrides default.
  94867. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94868. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94869. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94870. */
  94871. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94872. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94873. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94874. mesh.computeWorldMatrix(true);
  94875. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94876. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94877. };
  94878. /**
  94879. * Targets the given meshes with their children and updates zoom level accordingly.
  94880. * @param meshes The mesh to target.
  94881. * @param radius Optional. If a cached radius position already exists, overrides default.
  94882. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94883. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94884. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94885. */
  94886. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94887. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94888. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94889. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94890. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94891. for (var i = 0; i < meshes.length; i++) {
  94892. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94893. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94894. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94895. }
  94896. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94897. };
  94898. /**
  94899. * Targets the given mesh and updates zoom level accordingly.
  94900. * @param mesh The mesh to target.
  94901. * @param radius Optional. If a cached radius position already exists, overrides default.
  94902. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94903. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94904. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94905. */
  94906. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94907. var _this = this;
  94908. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94909. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94910. var zoomTarget;
  94911. if (!this._attachedCamera) {
  94912. return;
  94913. }
  94914. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94915. var bottom = minimumWorld.y;
  94916. var top = maximumWorld.y;
  94917. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94918. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94919. if (focusOnOriginXZ) {
  94920. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94921. }
  94922. else {
  94923. var centerWorld = minimumWorld.add(radiusWorld);
  94924. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94925. }
  94926. if (!this._vectorTransition) {
  94927. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94928. }
  94929. this._betaIsAnimating = true;
  94930. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94931. if (animatable) {
  94932. this._animatables.push(animatable);
  94933. }
  94934. // sets the radius and lower radius bounds
  94935. // Small delta ensures camera is not always at lower zoom limit.
  94936. var radius = 0;
  94937. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94938. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94939. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94940. radius = position;
  94941. }
  94942. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94943. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94944. if (this._attachedCamera.lowerRadiusLimit === null) {
  94945. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94946. }
  94947. }
  94948. // Set sensibilities
  94949. var extend = maximumWorld.subtract(minimumWorld).length();
  94950. this._attachedCamera.panningSensibility = 5000 / extend;
  94951. this._attachedCamera.wheelPrecision = 100 / radius;
  94952. // transition to new radius
  94953. if (!this._radiusTransition) {
  94954. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94955. }
  94956. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94957. _this.stopAllAnimations();
  94958. if (onAnimationEnd) {
  94959. onAnimationEnd();
  94960. }
  94961. if (_this._attachedCamera) {
  94962. _this._attachedCamera.storeState();
  94963. }
  94964. });
  94965. if (animatable) {
  94966. this._animatables.push(animatable);
  94967. }
  94968. };
  94969. /**
  94970. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94971. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94972. * frustum width.
  94973. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94974. * to fully enclose the mesh in the viewing frustum.
  94975. */
  94976. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94977. var size = maximumWorld.subtract(minimumWorld);
  94978. var boxVectorGlobalDiagonal = size.length();
  94979. var frustumSlope = this._getFrustumSlope();
  94980. // Formula for setting distance
  94981. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94982. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94983. // Horizon distance
  94984. var radius = radiusWithoutFraming * this._radiusScale;
  94985. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94986. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94987. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94988. var camera = this._attachedCamera;
  94989. if (!camera) {
  94990. return 0;
  94991. }
  94992. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94993. // Don't exceed the requested limit
  94994. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94995. }
  94996. // Don't exceed the upper radius limit
  94997. if (camera.upperRadiusLimit) {
  94998. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94999. }
  95000. return distance;
  95001. };
  95002. /**
  95003. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  95004. * is automatically returned to its default position (expected to be above ground plane).
  95005. */
  95006. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  95007. var _this = this;
  95008. if (this._elevationReturnTime < 0) {
  95009. return;
  95010. }
  95011. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  95012. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  95013. var limitBeta = Math.PI * 0.5;
  95014. // Bring the camera back up if below the ground plane
  95015. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  95016. this._betaIsAnimating = true;
  95017. //Transition to new position
  95018. this.stopAllAnimations();
  95019. if (!this._betaTransition) {
  95020. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  95021. }
  95022. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  95023. _this._clearAnimationLocks();
  95024. _this.stopAllAnimations();
  95025. });
  95026. if (animatabe) {
  95027. this._animatables.push(animatabe);
  95028. }
  95029. }
  95030. };
  95031. /**
  95032. * Returns the frustum slope based on the canvas ratio and camera FOV
  95033. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  95034. */
  95035. FramingBehavior.prototype._getFrustumSlope = function () {
  95036. // Calculate the viewport ratio
  95037. // Aspect Ratio is Height/Width.
  95038. var camera = this._attachedCamera;
  95039. if (!camera) {
  95040. return BABYLON.Vector2.Zero();
  95041. }
  95042. var engine = camera.getScene().getEngine();
  95043. var aspectRatio = engine.getAspectRatio(camera);
  95044. // Camera FOV is the vertical field of view (top-bottom) in radians.
  95045. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  95046. var frustumSlopeY = Math.tan(camera.fov / 2);
  95047. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  95048. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  95049. // along the forward vector.
  95050. var frustumSlopeX = frustumSlopeY * aspectRatio;
  95051. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  95052. };
  95053. /**
  95054. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  95055. */
  95056. FramingBehavior.prototype._clearAnimationLocks = function () {
  95057. this._betaIsAnimating = false;
  95058. };
  95059. /**
  95060. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95061. */
  95062. FramingBehavior.prototype._applyUserInteraction = function () {
  95063. if (this.isUserIsMoving) {
  95064. this._lastInteractionTime = BABYLON.Tools.Now;
  95065. this.stopAllAnimations();
  95066. this._clearAnimationLocks();
  95067. }
  95068. };
  95069. /**
  95070. * Stops and removes all animations that have been applied to the camera
  95071. */
  95072. FramingBehavior.prototype.stopAllAnimations = function () {
  95073. if (this._attachedCamera) {
  95074. this._attachedCamera.animations = [];
  95075. }
  95076. while (this._animatables.length) {
  95077. if (this._animatables[0]) {
  95078. this._animatables[0].onAnimationEnd = null;
  95079. this._animatables[0].stop();
  95080. }
  95081. this._animatables.shift();
  95082. }
  95083. };
  95084. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  95085. /**
  95086. * Gets a value indicating if the user is moving the camera
  95087. */
  95088. get: function () {
  95089. if (!this._attachedCamera) {
  95090. return false;
  95091. }
  95092. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95093. this._attachedCamera.inertialBetaOffset !== 0 ||
  95094. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95095. this._attachedCamera.inertialPanningX !== 0 ||
  95096. this._attachedCamera.inertialPanningY !== 0 ||
  95097. this._isPointerDown;
  95098. },
  95099. enumerable: true,
  95100. configurable: true
  95101. });
  95102. /**
  95103. * The easing function used by animations
  95104. */
  95105. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  95106. /**
  95107. * The easing mode used by animations
  95108. */
  95109. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  95110. // Statics
  95111. /**
  95112. * The camera can move all the way towards the mesh.
  95113. */
  95114. FramingBehavior.IgnoreBoundsSizeMode = 0;
  95115. /**
  95116. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  95117. */
  95118. FramingBehavior.FitFrustumSidesMode = 1;
  95119. return FramingBehavior;
  95120. }());
  95121. BABYLON.FramingBehavior = FramingBehavior;
  95122. })(BABYLON || (BABYLON = {}));
  95123. //# sourceMappingURL=babylon.framingBehavior.js.map
  95124. var BABYLON;
  95125. (function (BABYLON) {
  95126. /**
  95127. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  95128. */
  95129. var BouncingBehavior = /** @class */ (function () {
  95130. function BouncingBehavior() {
  95131. /**
  95132. * The duration of the animation, in milliseconds
  95133. */
  95134. this.transitionDuration = 450;
  95135. /**
  95136. * Length of the distance animated by the transition when lower radius is reached
  95137. */
  95138. this.lowerRadiusTransitionRange = 2;
  95139. /**
  95140. * Length of the distance animated by the transition when upper radius is reached
  95141. */
  95142. this.upperRadiusTransitionRange = -2;
  95143. this._autoTransitionRange = false;
  95144. // Animations
  95145. this._radiusIsAnimating = false;
  95146. this._radiusBounceTransition = null;
  95147. this._animatables = new Array();
  95148. }
  95149. Object.defineProperty(BouncingBehavior.prototype, "name", {
  95150. get: function () {
  95151. return "Bouncing";
  95152. },
  95153. enumerable: true,
  95154. configurable: true
  95155. });
  95156. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  95157. /**
  95158. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  95159. */
  95160. get: function () {
  95161. return this._autoTransitionRange;
  95162. },
  95163. /**
  95164. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  95165. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  95166. */
  95167. set: function (value) {
  95168. var _this = this;
  95169. if (this._autoTransitionRange === value) {
  95170. return;
  95171. }
  95172. this._autoTransitionRange = value;
  95173. var camera = this._attachedCamera;
  95174. if (!camera) {
  95175. return;
  95176. }
  95177. if (value) {
  95178. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  95179. if (!mesh) {
  95180. return;
  95181. }
  95182. mesh.computeWorldMatrix(true);
  95183. var diagonal = mesh.getBoundingInfo().diagonalLength;
  95184. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  95185. _this.upperRadiusTransitionRange = diagonal * 0.05;
  95186. });
  95187. }
  95188. else if (this._onMeshTargetChangedObserver) {
  95189. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95190. }
  95191. },
  95192. enumerable: true,
  95193. configurable: true
  95194. });
  95195. BouncingBehavior.prototype.init = function () {
  95196. // Do notihng
  95197. };
  95198. BouncingBehavior.prototype.attach = function (camera) {
  95199. var _this = this;
  95200. this._attachedCamera = camera;
  95201. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95202. if (!_this._attachedCamera) {
  95203. return;
  95204. }
  95205. // Add the bounce animation to the lower radius limit
  95206. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  95207. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  95208. }
  95209. // Add the bounce animation to the upper radius limit
  95210. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  95211. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  95212. }
  95213. });
  95214. };
  95215. BouncingBehavior.prototype.detach = function () {
  95216. if (!this._attachedCamera) {
  95217. return;
  95218. }
  95219. if (this._onAfterCheckInputsObserver) {
  95220. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95221. }
  95222. if (this._onMeshTargetChangedObserver) {
  95223. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95224. }
  95225. this._attachedCamera = null;
  95226. };
  95227. /**
  95228. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  95229. * @param radiusLimit The limit to check against.
  95230. * @return Bool to indicate if at limit.
  95231. */
  95232. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  95233. if (!this._attachedCamera) {
  95234. return false;
  95235. }
  95236. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  95237. return true;
  95238. }
  95239. return false;
  95240. };
  95241. /**
  95242. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  95243. * @param radiusDelta The delta by which to animate to. Can be negative.
  95244. */
  95245. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  95246. var _this = this;
  95247. if (!this._attachedCamera) {
  95248. return;
  95249. }
  95250. if (!this._radiusBounceTransition) {
  95251. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  95252. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  95253. }
  95254. // Prevent zoom until bounce has completed
  95255. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  95256. this._attachedCamera.wheelPrecision = Infinity;
  95257. this._attachedCamera.inertialRadiusOffset = 0;
  95258. // Animate to the radius limit
  95259. this.stopAllAnimations();
  95260. this._radiusIsAnimating = true;
  95261. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  95262. if (animatable) {
  95263. this._animatables.push(animatable);
  95264. }
  95265. };
  95266. /**
  95267. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  95268. */
  95269. BouncingBehavior.prototype._clearAnimationLocks = function () {
  95270. this._radiusIsAnimating = false;
  95271. if (this._attachedCamera) {
  95272. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  95273. }
  95274. };
  95275. /**
  95276. * Stops and removes all animations that have been applied to the camera
  95277. */
  95278. BouncingBehavior.prototype.stopAllAnimations = function () {
  95279. if (this._attachedCamera) {
  95280. this._attachedCamera.animations = [];
  95281. }
  95282. while (this._animatables.length) {
  95283. this._animatables[0].onAnimationEnd = null;
  95284. this._animatables[0].stop();
  95285. this._animatables.shift();
  95286. }
  95287. };
  95288. /**
  95289. * The easing function used by animations
  95290. */
  95291. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  95292. /**
  95293. * The easing mode used by animations
  95294. */
  95295. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  95296. return BouncingBehavior;
  95297. }());
  95298. BABYLON.BouncingBehavior = BouncingBehavior;
  95299. })(BABYLON || (BABYLON = {}));
  95300. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  95301. var BABYLON;
  95302. (function (BABYLON) {
  95303. var AutoRotationBehavior = /** @class */ (function () {
  95304. function AutoRotationBehavior() {
  95305. this._zoomStopsAnimation = false;
  95306. this._idleRotationSpeed = 0.05;
  95307. this._idleRotationWaitTime = 2000;
  95308. this._idleRotationSpinupTime = 2000;
  95309. this._isPointerDown = false;
  95310. this._lastFrameTime = null;
  95311. this._lastInteractionTime = -Infinity;
  95312. this._cameraRotationSpeed = 0;
  95313. this._lastFrameRadius = 0;
  95314. }
  95315. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  95316. get: function () {
  95317. return "AutoRotation";
  95318. },
  95319. enumerable: true,
  95320. configurable: true
  95321. });
  95322. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  95323. /**
  95324. * Gets the flag that indicates if user zooming should stop animation.
  95325. */
  95326. get: function () {
  95327. return this._zoomStopsAnimation;
  95328. },
  95329. /**
  95330. * Sets the flag that indicates if user zooming should stop animation.
  95331. */
  95332. set: function (flag) {
  95333. this._zoomStopsAnimation = flag;
  95334. },
  95335. enumerable: true,
  95336. configurable: true
  95337. });
  95338. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  95339. /**
  95340. * Gets the default speed at which the camera rotates around the model.
  95341. */
  95342. get: function () {
  95343. return this._idleRotationSpeed;
  95344. },
  95345. /**
  95346. * Sets the default speed at which the camera rotates around the model.
  95347. */
  95348. set: function (speed) {
  95349. this._idleRotationSpeed = speed;
  95350. },
  95351. enumerable: true,
  95352. configurable: true
  95353. });
  95354. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  95355. /**
  95356. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  95357. */
  95358. get: function () {
  95359. return this._idleRotationWaitTime;
  95360. },
  95361. /**
  95362. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  95363. */
  95364. set: function (time) {
  95365. this._idleRotationWaitTime = time;
  95366. },
  95367. enumerable: true,
  95368. configurable: true
  95369. });
  95370. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  95371. /**
  95372. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95373. */
  95374. get: function () {
  95375. return this._idleRotationSpinupTime;
  95376. },
  95377. /**
  95378. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95379. */
  95380. set: function (time) {
  95381. this._idleRotationSpinupTime = time;
  95382. },
  95383. enumerable: true,
  95384. configurable: true
  95385. });
  95386. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  95387. /**
  95388. * Gets a value indicating if the camera is currently rotating because of this behavior
  95389. */
  95390. get: function () {
  95391. return Math.abs(this._cameraRotationSpeed) > 0;
  95392. },
  95393. enumerable: true,
  95394. configurable: true
  95395. });
  95396. AutoRotationBehavior.prototype.init = function () {
  95397. // Do notihng
  95398. };
  95399. AutoRotationBehavior.prototype.attach = function (camera) {
  95400. var _this = this;
  95401. this._attachedCamera = camera;
  95402. var scene = this._attachedCamera.getScene();
  95403. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95404. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95405. _this._isPointerDown = true;
  95406. return;
  95407. }
  95408. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95409. _this._isPointerDown = false;
  95410. }
  95411. });
  95412. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95413. var now = BABYLON.Tools.Now;
  95414. var dt = 0;
  95415. if (_this._lastFrameTime != null) {
  95416. dt = now - _this._lastFrameTime;
  95417. }
  95418. _this._lastFrameTime = now;
  95419. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95420. _this._applyUserInteraction();
  95421. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  95422. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  95423. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  95424. // Step camera rotation by rotation speed
  95425. if (_this._attachedCamera) {
  95426. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  95427. }
  95428. });
  95429. };
  95430. AutoRotationBehavior.prototype.detach = function () {
  95431. if (!this._attachedCamera) {
  95432. return;
  95433. }
  95434. var scene = this._attachedCamera.getScene();
  95435. if (this._onPrePointerObservableObserver) {
  95436. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95437. }
  95438. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95439. this._attachedCamera = null;
  95440. };
  95441. /**
  95442. * Returns true if user is scrolling.
  95443. * @return true if user is scrolling.
  95444. */
  95445. AutoRotationBehavior.prototype._userIsZooming = function () {
  95446. if (!this._attachedCamera) {
  95447. return false;
  95448. }
  95449. return this._attachedCamera.inertialRadiusOffset !== 0;
  95450. };
  95451. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  95452. if (!this._attachedCamera) {
  95453. return false;
  95454. }
  95455. var zoomHasHitLimit = false;
  95456. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  95457. zoomHasHitLimit = true;
  95458. }
  95459. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  95460. this._lastFrameRadius = this._attachedCamera.radius;
  95461. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  95462. };
  95463. /**
  95464. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95465. */
  95466. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  95467. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  95468. this._lastInteractionTime = BABYLON.Tools.Now;
  95469. }
  95470. };
  95471. // Tools
  95472. AutoRotationBehavior.prototype._userIsMoving = function () {
  95473. if (!this._attachedCamera) {
  95474. return false;
  95475. }
  95476. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95477. this._attachedCamera.inertialBetaOffset !== 0 ||
  95478. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95479. this._attachedCamera.inertialPanningX !== 0 ||
  95480. this._attachedCamera.inertialPanningY !== 0 ||
  95481. this._isPointerDown;
  95482. };
  95483. return AutoRotationBehavior;
  95484. }());
  95485. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  95486. })(BABYLON || (BABYLON = {}));
  95487. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  95488. var BABYLON;
  95489. (function (BABYLON) {
  95490. var NullEngineOptions = /** @class */ (function () {
  95491. function NullEngineOptions() {
  95492. this.renderWidth = 512;
  95493. this.renderHeight = 256;
  95494. this.textureSize = 512;
  95495. this.deterministicLockstep = false;
  95496. this.lockstepMaxSteps = 4;
  95497. }
  95498. return NullEngineOptions;
  95499. }());
  95500. BABYLON.NullEngineOptions = NullEngineOptions;
  95501. /**
  95502. * The null engine class provides support for headless version of babylon.js.
  95503. * This can be used in server side scenario or for testing purposes
  95504. */
  95505. var NullEngine = /** @class */ (function (_super) {
  95506. __extends(NullEngine, _super);
  95507. function NullEngine(options) {
  95508. if (options === void 0) { options = new NullEngineOptions(); }
  95509. var _this = _super.call(this, null) || this;
  95510. if (options.deterministicLockstep === undefined) {
  95511. options.deterministicLockstep = false;
  95512. }
  95513. if (options.lockstepMaxSteps === undefined) {
  95514. options.lockstepMaxSteps = 4;
  95515. }
  95516. _this._options = options;
  95517. // Init caps
  95518. // We consider we are on a webgl1 capable device
  95519. _this._caps = new BABYLON.EngineCapabilities();
  95520. _this._caps.maxTexturesImageUnits = 16;
  95521. _this._caps.maxVertexTextureImageUnits = 16;
  95522. _this._caps.maxTextureSize = 512;
  95523. _this._caps.maxCubemapTextureSize = 512;
  95524. _this._caps.maxRenderTextureSize = 512;
  95525. _this._caps.maxVertexAttribs = 16;
  95526. _this._caps.maxVaryingVectors = 16;
  95527. _this._caps.maxFragmentUniformVectors = 16;
  95528. _this._caps.maxVertexUniformVectors = 16;
  95529. // Extensions
  95530. _this._caps.standardDerivatives = false;
  95531. _this._caps.astc = null;
  95532. _this._caps.s3tc = null;
  95533. _this._caps.pvrtc = null;
  95534. _this._caps.etc1 = null;
  95535. _this._caps.etc2 = null;
  95536. _this._caps.textureAnisotropicFilterExtension = null;
  95537. _this._caps.maxAnisotropy = 0;
  95538. _this._caps.uintIndices = false;
  95539. _this._caps.fragmentDepthSupported = false;
  95540. _this._caps.highPrecisionShaderSupported = true;
  95541. _this._caps.colorBufferFloat = false;
  95542. _this._caps.textureFloat = false;
  95543. _this._caps.textureFloatLinearFiltering = false;
  95544. _this._caps.textureFloatRender = false;
  95545. _this._caps.textureHalfFloat = false;
  95546. _this._caps.textureHalfFloatLinearFiltering = false;
  95547. _this._caps.textureHalfFloatRender = false;
  95548. _this._caps.textureLOD = false;
  95549. _this._caps.drawBuffersExtension = false;
  95550. _this._caps.depthTextureExtension = false;
  95551. _this._caps.vertexArrayObject = false;
  95552. _this._caps.instancedArrays = false;
  95553. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  95554. // Wrappers
  95555. if (typeof URL === "undefined") {
  95556. URL = {
  95557. createObjectURL: function () { },
  95558. revokeObjectURL: function () { }
  95559. };
  95560. }
  95561. if (typeof Blob === "undefined") {
  95562. Blob = function () { };
  95563. }
  95564. return _this;
  95565. }
  95566. NullEngine.prototype.isDeterministicLockStep = function () {
  95567. return this._options.deterministicLockstep;
  95568. };
  95569. NullEngine.prototype.getLockstepMaxSteps = function () {
  95570. return this._options.lockstepMaxSteps;
  95571. };
  95572. NullEngine.prototype.getHardwareScalingLevel = function () {
  95573. return 1.0;
  95574. };
  95575. NullEngine.prototype.createVertexBuffer = function (vertices) {
  95576. return {
  95577. capacity: 0,
  95578. references: 1,
  95579. is32Bits: false
  95580. };
  95581. };
  95582. NullEngine.prototype.createIndexBuffer = function (indices) {
  95583. return {
  95584. capacity: 0,
  95585. references: 1,
  95586. is32Bits: false
  95587. };
  95588. };
  95589. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  95590. if (stencil === void 0) { stencil = false; }
  95591. };
  95592. NullEngine.prototype.getRenderWidth = function (useScreen) {
  95593. if (useScreen === void 0) { useScreen = false; }
  95594. if (!useScreen && this._currentRenderTarget) {
  95595. return this._currentRenderTarget.width;
  95596. }
  95597. return this._options.renderWidth;
  95598. };
  95599. NullEngine.prototype.getRenderHeight = function (useScreen) {
  95600. if (useScreen === void 0) { useScreen = false; }
  95601. if (!useScreen && this._currentRenderTarget) {
  95602. return this._currentRenderTarget.height;
  95603. }
  95604. return this._options.renderHeight;
  95605. };
  95606. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  95607. this._cachedViewport = viewport;
  95608. };
  95609. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  95610. return {
  95611. transformFeedback: null,
  95612. __SPECTOR_rebuildProgram: null
  95613. };
  95614. };
  95615. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95616. return [];
  95617. };
  95618. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95619. return [];
  95620. };
  95621. NullEngine.prototype.bindSamplers = function (effect) {
  95622. this._currentEffect = null;
  95623. };
  95624. NullEngine.prototype.enableEffect = function (effect) {
  95625. this._currentEffect = effect;
  95626. if (effect.onBind) {
  95627. effect.onBind(effect);
  95628. }
  95629. effect.onBindObservable.notifyObservers(effect);
  95630. };
  95631. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95632. if (zOffset === void 0) { zOffset = 0; }
  95633. if (reverseSide === void 0) { reverseSide = false; }
  95634. };
  95635. NullEngine.prototype.setIntArray = function (uniform, array) {
  95636. };
  95637. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95638. };
  95639. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95640. };
  95641. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95642. };
  95643. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95644. };
  95645. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95646. };
  95647. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95648. };
  95649. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95650. };
  95651. NullEngine.prototype.setArray = function (uniform, array) {
  95652. };
  95653. NullEngine.prototype.setArray2 = function (uniform, array) {
  95654. };
  95655. NullEngine.prototype.setArray3 = function (uniform, array) {
  95656. };
  95657. NullEngine.prototype.setArray4 = function (uniform, array) {
  95658. };
  95659. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95660. };
  95661. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95662. };
  95663. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95664. };
  95665. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95666. };
  95667. NullEngine.prototype.setFloat = function (uniform, value) {
  95668. };
  95669. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95670. };
  95671. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95672. };
  95673. NullEngine.prototype.setBool = function (uniform, bool) {
  95674. };
  95675. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95676. };
  95677. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95678. };
  95679. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95680. };
  95681. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95682. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95683. if (this._alphaMode === mode) {
  95684. return;
  95685. }
  95686. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95687. if (!noDepthWriteChange) {
  95688. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95689. }
  95690. this._alphaMode = mode;
  95691. };
  95692. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95693. };
  95694. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95695. if (this.preventCacheWipeBetweenFrames) {
  95696. return;
  95697. }
  95698. this.resetTextureCache();
  95699. this._currentEffect = null;
  95700. if (bruteForce) {
  95701. this._currentProgram = null;
  95702. this._stencilState.reset();
  95703. this._depthCullingState.reset();
  95704. this._alphaState.reset();
  95705. }
  95706. this._cachedVertexBuffers = null;
  95707. this._cachedIndexBuffer = null;
  95708. this._cachedEffectForVertexBuffers = null;
  95709. };
  95710. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95711. };
  95712. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95713. };
  95714. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95715. };
  95716. NullEngine.prototype._createTexture = function () {
  95717. return {};
  95718. };
  95719. NullEngine.prototype._releaseTexture = function (texture) {
  95720. };
  95721. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95722. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95723. if (onLoad === void 0) { onLoad = null; }
  95724. if (onError === void 0) { onError = null; }
  95725. if (buffer === void 0) { buffer = null; }
  95726. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95727. var url = String(urlArg);
  95728. texture.url = url;
  95729. texture.generateMipMaps = !noMipmap;
  95730. texture.samplingMode = samplingMode;
  95731. texture.invertY = invertY;
  95732. texture.baseWidth = this._options.textureSize;
  95733. texture.baseHeight = this._options.textureSize;
  95734. texture.width = this._options.textureSize;
  95735. texture.height = this._options.textureSize;
  95736. if (format) {
  95737. texture.format = format;
  95738. }
  95739. texture.isReady = true;
  95740. if (onLoad) {
  95741. onLoad();
  95742. }
  95743. this._internalTexturesCache.push(texture);
  95744. return texture;
  95745. };
  95746. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95747. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95748. if (options !== undefined && typeof options === "object") {
  95749. fullOptions.generateMipMaps = options.generateMipMaps;
  95750. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95751. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95752. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95753. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95754. }
  95755. else {
  95756. fullOptions.generateMipMaps = options;
  95757. fullOptions.generateDepthBuffer = true;
  95758. fullOptions.generateStencilBuffer = false;
  95759. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95760. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95761. }
  95762. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95763. var width = size.width || size;
  95764. var height = size.height || size;
  95765. texture._depthStencilBuffer = {};
  95766. texture._framebuffer = {};
  95767. texture.baseWidth = width;
  95768. texture.baseHeight = height;
  95769. texture.width = width;
  95770. texture.height = height;
  95771. texture.isReady = true;
  95772. texture.samples = 1;
  95773. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95774. texture.samplingMode = fullOptions.samplingMode;
  95775. texture.type = fullOptions.type;
  95776. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95777. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95778. this._internalTexturesCache.push(texture);
  95779. return texture;
  95780. };
  95781. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95782. texture.samplingMode = samplingMode;
  95783. };
  95784. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95785. if (this._currentRenderTarget) {
  95786. this.unBindFramebuffer(this._currentRenderTarget);
  95787. }
  95788. this._currentRenderTarget = texture;
  95789. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95790. if (this._cachedViewport && !forceFullscreenViewport) {
  95791. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95792. }
  95793. };
  95794. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95795. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95796. this._currentRenderTarget = null;
  95797. if (onBeforeUnbind) {
  95798. if (texture._MSAAFramebuffer) {
  95799. this._currentFramebuffer = texture._framebuffer;
  95800. }
  95801. onBeforeUnbind();
  95802. }
  95803. this._currentFramebuffer = null;
  95804. };
  95805. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95806. var vbo = {
  95807. capacity: 1,
  95808. references: 1,
  95809. is32Bits: false
  95810. };
  95811. return vbo;
  95812. };
  95813. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95814. if (offset === void 0) { offset = 0; }
  95815. };
  95816. /**
  95817. * Updates a dynamic vertex buffer.
  95818. * @param vertexBuffer the vertex buffer to update
  95819. * @param data the data used to update the vertex buffer
  95820. * @param byteOffset the byte offset of the data (optional)
  95821. * @param byteLength the byte length of the data (optional)
  95822. */
  95823. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95824. };
  95825. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95826. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95827. this._boundTexturesCache[this._activeChannel] = texture;
  95828. }
  95829. };
  95830. NullEngine.prototype._bindTexture = function (channel, texture) {
  95831. if (channel < 0) {
  95832. return;
  95833. }
  95834. this._bindTextureDirectly(0, texture);
  95835. };
  95836. NullEngine.prototype._releaseBuffer = function (buffer) {
  95837. buffer.references--;
  95838. if (buffer.references === 0) {
  95839. return true;
  95840. }
  95841. return false;
  95842. };
  95843. NullEngine.prototype.releaseEffects = function () {
  95844. };
  95845. return NullEngine;
  95846. }(BABYLON.Engine));
  95847. BABYLON.NullEngine = NullEngine;
  95848. })(BABYLON || (BABYLON = {}));
  95849. //# sourceMappingURL=babylon.nullEngine.js.map
  95850. var BABYLON;
  95851. (function (BABYLON) {
  95852. /**
  95853. * This class can be used to get instrumentation data from a Babylon engine
  95854. */
  95855. var EngineInstrumentation = /** @class */ (function () {
  95856. function EngineInstrumentation(engine) {
  95857. this.engine = engine;
  95858. this._captureGPUFrameTime = false;
  95859. this._gpuFrameTime = new BABYLON.PerfCounter();
  95860. this._captureShaderCompilationTime = false;
  95861. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95862. // Observers
  95863. this._onBeginFrameObserver = null;
  95864. this._onEndFrameObserver = null;
  95865. this._onBeforeShaderCompilationObserver = null;
  95866. this._onAfterShaderCompilationObserver = null;
  95867. }
  95868. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95869. // Properties
  95870. /**
  95871. * Gets the perf counter used for GPU frame time
  95872. */
  95873. get: function () {
  95874. return this._gpuFrameTime;
  95875. },
  95876. enumerable: true,
  95877. configurable: true
  95878. });
  95879. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95880. /**
  95881. * Gets the GPU frame time capture status
  95882. */
  95883. get: function () {
  95884. return this._captureGPUFrameTime;
  95885. },
  95886. /**
  95887. * Enable or disable the GPU frame time capture
  95888. */
  95889. set: function (value) {
  95890. var _this = this;
  95891. if (value === this._captureGPUFrameTime) {
  95892. return;
  95893. }
  95894. this._captureGPUFrameTime = value;
  95895. if (value) {
  95896. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95897. if (!_this._gpuFrameTimeToken) {
  95898. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95899. }
  95900. });
  95901. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95902. if (!_this._gpuFrameTimeToken) {
  95903. return;
  95904. }
  95905. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95906. if (time > -1) {
  95907. _this._gpuFrameTimeToken = null;
  95908. _this._gpuFrameTime.fetchNewFrame();
  95909. _this._gpuFrameTime.addCount(time, true);
  95910. }
  95911. });
  95912. }
  95913. else {
  95914. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95915. this._onBeginFrameObserver = null;
  95916. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95917. this._onEndFrameObserver = null;
  95918. }
  95919. },
  95920. enumerable: true,
  95921. configurable: true
  95922. });
  95923. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95924. /**
  95925. * Gets the perf counter used for shader compilation time
  95926. */
  95927. get: function () {
  95928. return this._shaderCompilationTime;
  95929. },
  95930. enumerable: true,
  95931. configurable: true
  95932. });
  95933. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95934. /**
  95935. * Gets the shader compilation time capture status
  95936. */
  95937. get: function () {
  95938. return this._captureShaderCompilationTime;
  95939. },
  95940. /**
  95941. * Enable or disable the shader compilation time capture
  95942. */
  95943. set: function (value) {
  95944. var _this = this;
  95945. if (value === this._captureShaderCompilationTime) {
  95946. return;
  95947. }
  95948. this._captureShaderCompilationTime = value;
  95949. if (value) {
  95950. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95951. _this._shaderCompilationTime.fetchNewFrame();
  95952. _this._shaderCompilationTime.beginMonitoring();
  95953. });
  95954. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95955. _this._shaderCompilationTime.endMonitoring();
  95956. });
  95957. }
  95958. else {
  95959. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95960. this._onBeforeShaderCompilationObserver = null;
  95961. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95962. this._onAfterShaderCompilationObserver = null;
  95963. }
  95964. },
  95965. enumerable: true,
  95966. configurable: true
  95967. });
  95968. EngineInstrumentation.prototype.dispose = function () {
  95969. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95970. this._onBeginFrameObserver = null;
  95971. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95972. this._onEndFrameObserver = null;
  95973. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95974. this._onBeforeShaderCompilationObserver = null;
  95975. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95976. this._onAfterShaderCompilationObserver = null;
  95977. this.engine = null;
  95978. };
  95979. return EngineInstrumentation;
  95980. }());
  95981. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95982. })(BABYLON || (BABYLON = {}));
  95983. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95984. var BABYLON;
  95985. (function (BABYLON) {
  95986. /**
  95987. * This class can be used to get instrumentation data from a Babylon engine
  95988. */
  95989. var SceneInstrumentation = /** @class */ (function () {
  95990. function SceneInstrumentation(scene) {
  95991. var _this = this;
  95992. this.scene = scene;
  95993. this._captureActiveMeshesEvaluationTime = false;
  95994. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95995. this._captureRenderTargetsRenderTime = false;
  95996. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95997. this._captureFrameTime = false;
  95998. this._frameTime = new BABYLON.PerfCounter();
  95999. this._captureRenderTime = false;
  96000. this._renderTime = new BABYLON.PerfCounter();
  96001. this._captureInterFrameTime = false;
  96002. this._interFrameTime = new BABYLON.PerfCounter();
  96003. this._captureParticlesRenderTime = false;
  96004. this._particlesRenderTime = new BABYLON.PerfCounter();
  96005. this._captureSpritesRenderTime = false;
  96006. this._spritesRenderTime = new BABYLON.PerfCounter();
  96007. this._capturePhysicsTime = false;
  96008. this._physicsTime = new BABYLON.PerfCounter();
  96009. this._captureAnimationsTime = false;
  96010. this._animationsTime = new BABYLON.PerfCounter();
  96011. // Observers
  96012. this._onBeforeActiveMeshesEvaluationObserver = null;
  96013. this._onAfterActiveMeshesEvaluationObserver = null;
  96014. this._onBeforeRenderTargetsRenderObserver = null;
  96015. this._onAfterRenderTargetsRenderObserver = null;
  96016. this._onAfterRenderObserver = null;
  96017. this._onBeforeDrawPhaseObserver = null;
  96018. this._onAfterDrawPhaseObserver = null;
  96019. this._onBeforeAnimationsObserver = null;
  96020. this._onBeforeParticlesRenderingObserver = null;
  96021. this._onAfterParticlesRenderingObserver = null;
  96022. this._onBeforeSpritesRenderingObserver = null;
  96023. this._onAfterSpritesRenderingObserver = null;
  96024. this._onBeforePhysicsObserver = null;
  96025. this._onAfterPhysicsObserver = null;
  96026. this._onAfterAnimationsObserver = null;
  96027. // Before render
  96028. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  96029. if (_this._captureActiveMeshesEvaluationTime) {
  96030. _this._activeMeshesEvaluationTime.fetchNewFrame();
  96031. }
  96032. if (_this._captureRenderTargetsRenderTime) {
  96033. _this._renderTargetsRenderTime.fetchNewFrame();
  96034. }
  96035. if (_this._captureFrameTime) {
  96036. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  96037. _this._frameTime.beginMonitoring();
  96038. }
  96039. if (_this._captureInterFrameTime) {
  96040. _this._interFrameTime.endMonitoring();
  96041. }
  96042. if (_this._captureParticlesRenderTime) {
  96043. _this._particlesRenderTime.fetchNewFrame();
  96044. }
  96045. if (_this._captureSpritesRenderTime) {
  96046. _this._spritesRenderTime.fetchNewFrame();
  96047. }
  96048. if (_this._captureAnimationsTime) {
  96049. _this._animationsTime.beginMonitoring();
  96050. }
  96051. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  96052. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  96053. });
  96054. // After render
  96055. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  96056. if (_this._captureFrameTime) {
  96057. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  96058. _this._frameTime.endMonitoring();
  96059. }
  96060. if (_this._captureRenderTime) {
  96061. _this._renderTime.endMonitoring(false);
  96062. }
  96063. if (_this._captureInterFrameTime) {
  96064. _this._interFrameTime.beginMonitoring();
  96065. }
  96066. });
  96067. }
  96068. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  96069. // Properties
  96070. /**
  96071. * Gets the perf counter used for active meshes evaluation time
  96072. */
  96073. get: function () {
  96074. return this._activeMeshesEvaluationTime;
  96075. },
  96076. enumerable: true,
  96077. configurable: true
  96078. });
  96079. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  96080. /**
  96081. * Gets the active meshes evaluation time capture status
  96082. */
  96083. get: function () {
  96084. return this._captureActiveMeshesEvaluationTime;
  96085. },
  96086. /**
  96087. * Enable or disable the active meshes evaluation time capture
  96088. */
  96089. set: function (value) {
  96090. var _this = this;
  96091. if (value === this._captureActiveMeshesEvaluationTime) {
  96092. return;
  96093. }
  96094. this._captureActiveMeshesEvaluationTime = value;
  96095. if (value) {
  96096. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  96097. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  96098. _this._activeMeshesEvaluationTime.beginMonitoring();
  96099. });
  96100. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  96101. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  96102. _this._activeMeshesEvaluationTime.endMonitoring();
  96103. });
  96104. }
  96105. else {
  96106. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96107. this._onBeforeActiveMeshesEvaluationObserver = null;
  96108. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96109. this._onAfterActiveMeshesEvaluationObserver = null;
  96110. }
  96111. },
  96112. enumerable: true,
  96113. configurable: true
  96114. });
  96115. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  96116. /**
  96117. * Gets the perf counter used for render targets render time
  96118. */
  96119. get: function () {
  96120. return this._renderTargetsRenderTime;
  96121. },
  96122. enumerable: true,
  96123. configurable: true
  96124. });
  96125. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  96126. /**
  96127. * Gets the render targets render time capture status
  96128. */
  96129. get: function () {
  96130. return this._captureRenderTargetsRenderTime;
  96131. },
  96132. /**
  96133. * Enable or disable the render targets render time capture
  96134. */
  96135. set: function (value) {
  96136. var _this = this;
  96137. if (value === this._captureRenderTargetsRenderTime) {
  96138. return;
  96139. }
  96140. this._captureRenderTargetsRenderTime = value;
  96141. if (value) {
  96142. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  96143. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  96144. _this._renderTargetsRenderTime.beginMonitoring();
  96145. });
  96146. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  96147. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  96148. _this._renderTargetsRenderTime.endMonitoring(false);
  96149. });
  96150. }
  96151. else {
  96152. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96153. this._onBeforeRenderTargetsRenderObserver = null;
  96154. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96155. this._onAfterRenderTargetsRenderObserver = null;
  96156. }
  96157. },
  96158. enumerable: true,
  96159. configurable: true
  96160. });
  96161. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  96162. /**
  96163. * Gets the perf counter used for particles render time
  96164. */
  96165. get: function () {
  96166. return this._particlesRenderTime;
  96167. },
  96168. enumerable: true,
  96169. configurable: true
  96170. });
  96171. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  96172. /**
  96173. * Gets the particles render time capture status
  96174. */
  96175. get: function () {
  96176. return this._captureParticlesRenderTime;
  96177. },
  96178. /**
  96179. * Enable or disable the particles render time capture
  96180. */
  96181. set: function (value) {
  96182. var _this = this;
  96183. if (value === this._captureParticlesRenderTime) {
  96184. return;
  96185. }
  96186. this._captureParticlesRenderTime = value;
  96187. if (value) {
  96188. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  96189. BABYLON.Tools.StartPerformanceCounter("Particles");
  96190. _this._particlesRenderTime.beginMonitoring();
  96191. });
  96192. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  96193. BABYLON.Tools.EndPerformanceCounter("Particles");
  96194. _this._particlesRenderTime.endMonitoring(false);
  96195. });
  96196. }
  96197. else {
  96198. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96199. this._onBeforeParticlesRenderingObserver = null;
  96200. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96201. this._onAfterParticlesRenderingObserver = null;
  96202. }
  96203. },
  96204. enumerable: true,
  96205. configurable: true
  96206. });
  96207. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  96208. /**
  96209. * Gets the perf counter used for sprites render time
  96210. */
  96211. get: function () {
  96212. return this._spritesRenderTime;
  96213. },
  96214. enumerable: true,
  96215. configurable: true
  96216. });
  96217. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  96218. /**
  96219. * Gets the sprites render time capture status
  96220. */
  96221. get: function () {
  96222. return this._captureSpritesRenderTime;
  96223. },
  96224. /**
  96225. * Enable or disable the sprites render time capture
  96226. */
  96227. set: function (value) {
  96228. var _this = this;
  96229. if (value === this._captureSpritesRenderTime) {
  96230. return;
  96231. }
  96232. this._captureSpritesRenderTime = value;
  96233. if (value) {
  96234. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  96235. BABYLON.Tools.StartPerformanceCounter("Sprites");
  96236. _this._spritesRenderTime.beginMonitoring();
  96237. });
  96238. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  96239. BABYLON.Tools.EndPerformanceCounter("Sprites");
  96240. _this._spritesRenderTime.endMonitoring(false);
  96241. });
  96242. }
  96243. else {
  96244. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96245. this._onBeforeSpritesRenderingObserver = null;
  96246. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96247. this._onAfterSpritesRenderingObserver = null;
  96248. }
  96249. },
  96250. enumerable: true,
  96251. configurable: true
  96252. });
  96253. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  96254. /**
  96255. * Gets the perf counter used for physics time
  96256. */
  96257. get: function () {
  96258. return this._physicsTime;
  96259. },
  96260. enumerable: true,
  96261. configurable: true
  96262. });
  96263. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  96264. /**
  96265. * Gets the physics time capture status
  96266. */
  96267. get: function () {
  96268. return this._capturePhysicsTime;
  96269. },
  96270. /**
  96271. * Enable or disable the physics time capture
  96272. */
  96273. set: function (value) {
  96274. var _this = this;
  96275. if (value === this._capturePhysicsTime) {
  96276. return;
  96277. }
  96278. this._capturePhysicsTime = value;
  96279. if (value) {
  96280. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  96281. BABYLON.Tools.StartPerformanceCounter("Physics");
  96282. _this._physicsTime.beginMonitoring();
  96283. });
  96284. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  96285. BABYLON.Tools.EndPerformanceCounter("Physics");
  96286. _this._physicsTime.endMonitoring();
  96287. });
  96288. }
  96289. else {
  96290. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96291. this._onBeforePhysicsObserver = null;
  96292. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96293. this._onAfterPhysicsObserver = null;
  96294. }
  96295. },
  96296. enumerable: true,
  96297. configurable: true
  96298. });
  96299. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  96300. /**
  96301. * Gets the perf counter used for animations time
  96302. */
  96303. get: function () {
  96304. return this._animationsTime;
  96305. },
  96306. enumerable: true,
  96307. configurable: true
  96308. });
  96309. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  96310. /**
  96311. * Gets the animations time capture status
  96312. */
  96313. get: function () {
  96314. return this._captureAnimationsTime;
  96315. },
  96316. /**
  96317. * Enable or disable the animations time capture
  96318. */
  96319. set: function (value) {
  96320. var _this = this;
  96321. if (value === this._captureAnimationsTime) {
  96322. return;
  96323. }
  96324. this._captureAnimationsTime = value;
  96325. if (value) {
  96326. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  96327. _this._animationsTime.endMonitoring();
  96328. });
  96329. }
  96330. else {
  96331. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96332. this._onAfterAnimationsObserver = null;
  96333. }
  96334. },
  96335. enumerable: true,
  96336. configurable: true
  96337. });
  96338. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  96339. /**
  96340. * Gets the perf counter used for frame time capture
  96341. */
  96342. get: function () {
  96343. return this._frameTime;
  96344. },
  96345. enumerable: true,
  96346. configurable: true
  96347. });
  96348. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  96349. /**
  96350. * Gets the frame time capture status
  96351. */
  96352. get: function () {
  96353. return this._captureFrameTime;
  96354. },
  96355. /**
  96356. * Enable or disable the frame time capture
  96357. */
  96358. set: function (value) {
  96359. this._captureFrameTime = value;
  96360. },
  96361. enumerable: true,
  96362. configurable: true
  96363. });
  96364. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  96365. /**
  96366. * Gets the perf counter used for inter-frames time capture
  96367. */
  96368. get: function () {
  96369. return this._interFrameTime;
  96370. },
  96371. enumerable: true,
  96372. configurable: true
  96373. });
  96374. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  96375. /**
  96376. * Gets the inter-frames time capture status
  96377. */
  96378. get: function () {
  96379. return this._captureInterFrameTime;
  96380. },
  96381. /**
  96382. * Enable or disable the inter-frames time capture
  96383. */
  96384. set: function (value) {
  96385. this._captureInterFrameTime = value;
  96386. },
  96387. enumerable: true,
  96388. configurable: true
  96389. });
  96390. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  96391. /**
  96392. * Gets the perf counter used for render time capture
  96393. */
  96394. get: function () {
  96395. return this._renderTime;
  96396. },
  96397. enumerable: true,
  96398. configurable: true
  96399. });
  96400. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  96401. /**
  96402. * Gets the render time capture status
  96403. */
  96404. get: function () {
  96405. return this._captureRenderTime;
  96406. },
  96407. /**
  96408. * Enable or disable the render time capture
  96409. */
  96410. set: function (value) {
  96411. var _this = this;
  96412. if (value === this._captureRenderTime) {
  96413. return;
  96414. }
  96415. this._captureRenderTime = value;
  96416. if (value) {
  96417. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  96418. _this._renderTime.beginMonitoring();
  96419. BABYLON.Tools.StartPerformanceCounter("Main render");
  96420. });
  96421. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  96422. _this._renderTime.endMonitoring(false);
  96423. BABYLON.Tools.EndPerformanceCounter("Main render");
  96424. });
  96425. }
  96426. else {
  96427. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96428. this._onBeforeDrawPhaseObserver = null;
  96429. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96430. this._onAfterDrawPhaseObserver = null;
  96431. }
  96432. },
  96433. enumerable: true,
  96434. configurable: true
  96435. });
  96436. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  96437. /**
  96438. * Gets the perf counter used for draw calls
  96439. */
  96440. get: function () {
  96441. return this.scene.getEngine()._drawCalls;
  96442. },
  96443. enumerable: true,
  96444. configurable: true
  96445. });
  96446. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  96447. /**
  96448. * Gets the perf counter used for texture collisions
  96449. */
  96450. get: function () {
  96451. return this.scene.getEngine()._textureCollisions;
  96452. },
  96453. enumerable: true,
  96454. configurable: true
  96455. });
  96456. SceneInstrumentation.prototype.dispose = function () {
  96457. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96458. this._onAfterRenderObserver = null;
  96459. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96460. this._onBeforeActiveMeshesEvaluationObserver = null;
  96461. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96462. this._onAfterActiveMeshesEvaluationObserver = null;
  96463. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96464. this._onBeforeRenderTargetsRenderObserver = null;
  96465. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96466. this._onAfterRenderTargetsRenderObserver = null;
  96467. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  96468. this._onBeforeAnimationsObserver = null;
  96469. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96470. this._onBeforeParticlesRenderingObserver = null;
  96471. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96472. this._onAfterParticlesRenderingObserver = null;
  96473. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96474. this._onBeforeSpritesRenderingObserver = null;
  96475. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96476. this._onAfterSpritesRenderingObserver = null;
  96477. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96478. this._onBeforeDrawPhaseObserver = null;
  96479. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96480. this._onAfterDrawPhaseObserver = null;
  96481. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96482. this._onBeforePhysicsObserver = null;
  96483. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96484. this._onAfterPhysicsObserver = null;
  96485. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96486. this._onAfterAnimationsObserver = null;
  96487. this.scene = null;
  96488. };
  96489. return SceneInstrumentation;
  96490. }());
  96491. BABYLON.SceneInstrumentation = SceneInstrumentation;
  96492. })(BABYLON || (BABYLON = {}));
  96493. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  96494. var BABYLON;
  96495. (function (BABYLON) {
  96496. /**
  96497. * @hidden
  96498. **/
  96499. var _TimeToken = /** @class */ (function () {
  96500. function _TimeToken() {
  96501. this._timeElapsedQueryEnded = false;
  96502. }
  96503. return _TimeToken;
  96504. }());
  96505. BABYLON._TimeToken = _TimeToken;
  96506. })(BABYLON || (BABYLON = {}));
  96507. //# sourceMappingURL=babylon.timeToken.js.map
  96508. var BABYLON;
  96509. (function (BABYLON) {
  96510. /**
  96511. * Background material defines definition.
  96512. * @hidden Mainly internal Use
  96513. */
  96514. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  96515. __extends(BackgroundMaterialDefines, _super);
  96516. /**
  96517. * Constructor of the defines.
  96518. */
  96519. function BackgroundMaterialDefines() {
  96520. var _this = _super.call(this) || this;
  96521. /**
  96522. * True if the diffuse texture is in use.
  96523. */
  96524. _this.DIFFUSE = false;
  96525. /**
  96526. * The direct UV channel to use.
  96527. */
  96528. _this.DIFFUSEDIRECTUV = 0;
  96529. /**
  96530. * True if the diffuse texture is in gamma space.
  96531. */
  96532. _this.GAMMADIFFUSE = false;
  96533. /**
  96534. * True if the diffuse texture has opacity in the alpha channel.
  96535. */
  96536. _this.DIFFUSEHASALPHA = false;
  96537. /**
  96538. * True if you want the material to fade to transparent at grazing angle.
  96539. */
  96540. _this.OPACITYFRESNEL = false;
  96541. /**
  96542. * True if an extra blur needs to be added in the reflection.
  96543. */
  96544. _this.REFLECTIONBLUR = false;
  96545. /**
  96546. * True if you want the material to fade to reflection at grazing angle.
  96547. */
  96548. _this.REFLECTIONFRESNEL = false;
  96549. /**
  96550. * True if you want the material to falloff as far as you move away from the scene center.
  96551. */
  96552. _this.REFLECTIONFALLOFF = false;
  96553. /**
  96554. * False if the current Webgl implementation does not support the texture lod extension.
  96555. */
  96556. _this.TEXTURELODSUPPORT = false;
  96557. /**
  96558. * True to ensure the data are premultiplied.
  96559. */
  96560. _this.PREMULTIPLYALPHA = false;
  96561. /**
  96562. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  96563. */
  96564. _this.USERGBCOLOR = false;
  96565. /**
  96566. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  96567. * stays aligned with the desired configuration.
  96568. */
  96569. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  96570. /**
  96571. * True to add noise in order to reduce the banding effect.
  96572. */
  96573. _this.NOISE = false;
  96574. /**
  96575. * is the reflection texture in BGR color scheme?
  96576. * Mainly used to solve a bug in ios10 video tag
  96577. */
  96578. _this.REFLECTIONBGR = false;
  96579. _this.IMAGEPROCESSING = false;
  96580. _this.VIGNETTE = false;
  96581. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  96582. _this.VIGNETTEBLENDMODEOPAQUE = false;
  96583. _this.TONEMAPPING = false;
  96584. _this.CONTRAST = false;
  96585. _this.COLORCURVES = false;
  96586. _this.COLORGRADING = false;
  96587. _this.COLORGRADING3D = false;
  96588. _this.SAMPLER3DGREENDEPTH = false;
  96589. _this.SAMPLER3DBGRMAP = false;
  96590. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  96591. _this.EXPOSURE = false;
  96592. // Reflection.
  96593. _this.REFLECTION = false;
  96594. _this.REFLECTIONMAP_3D = false;
  96595. _this.REFLECTIONMAP_SPHERICAL = false;
  96596. _this.REFLECTIONMAP_PLANAR = false;
  96597. _this.REFLECTIONMAP_CUBIC = false;
  96598. _this.REFLECTIONMAP_PROJECTION = false;
  96599. _this.REFLECTIONMAP_SKYBOX = false;
  96600. _this.REFLECTIONMAP_EXPLICIT = false;
  96601. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96602. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96603. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96604. _this.INVERTCUBICMAP = false;
  96605. _this.REFLECTIONMAP_OPPOSITEZ = false;
  96606. _this.LODINREFLECTIONALPHA = false;
  96607. _this.GAMMAREFLECTION = false;
  96608. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  96609. // Default BJS.
  96610. _this.MAINUV1 = false;
  96611. _this.MAINUV2 = false;
  96612. _this.UV1 = false;
  96613. _this.UV2 = false;
  96614. _this.CLIPPLANE = false;
  96615. _this.POINTSIZE = false;
  96616. _this.FOG = false;
  96617. _this.NORMAL = false;
  96618. _this.NUM_BONE_INFLUENCERS = 0;
  96619. _this.BonesPerMesh = 0;
  96620. _this.INSTANCES = false;
  96621. _this.SHADOWFLOAT = false;
  96622. _this.rebuild();
  96623. return _this;
  96624. }
  96625. return BackgroundMaterialDefines;
  96626. }(BABYLON.MaterialDefines));
  96627. /**
  96628. * Background material used to create an efficient environement around your scene.
  96629. */
  96630. var BackgroundMaterial = /** @class */ (function (_super) {
  96631. __extends(BackgroundMaterial, _super);
  96632. /**
  96633. * Instantiates a Background Material in the given scene
  96634. * @param name The friendly name of the material
  96635. * @param scene The scene to add the material to
  96636. */
  96637. function BackgroundMaterial(name, scene) {
  96638. var _this = _super.call(this, name, scene) || this;
  96639. /**
  96640. * Key light Color (multiply against the environement texture)
  96641. */
  96642. _this.primaryColor = BABYLON.Color3.White();
  96643. _this._primaryColorShadowLevel = 0;
  96644. _this._primaryColorHighlightLevel = 0;
  96645. /**
  96646. * Reflection Texture used in the material.
  96647. * Should be author in a specific way for the best result (refer to the documentation).
  96648. */
  96649. _this.reflectionTexture = null;
  96650. /**
  96651. * Reflection Texture level of blur.
  96652. *
  96653. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96654. * texture twice.
  96655. */
  96656. _this.reflectionBlur = 0;
  96657. /**
  96658. * Diffuse Texture used in the material.
  96659. * Should be author in a specific way for the best result (refer to the documentation).
  96660. */
  96661. _this.diffuseTexture = null;
  96662. _this._shadowLights = null;
  96663. /**
  96664. * Specify the list of lights casting shadow on the material.
  96665. * All scene shadow lights will be included if null.
  96666. */
  96667. _this.shadowLights = null;
  96668. /**
  96669. * Helps adjusting the shadow to a softer level if required.
  96670. * 0 means black shadows and 1 means no shadows.
  96671. */
  96672. _this.shadowLevel = 0;
  96673. /**
  96674. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96675. * It is usually zero but might be interesting to modify according to your setup.
  96676. */
  96677. _this.sceneCenter = BABYLON.Vector3.Zero();
  96678. /**
  96679. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96680. * This helps ensuring a nice transition when the camera goes under the ground.
  96681. */
  96682. _this.opacityFresnel = true;
  96683. /**
  96684. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96685. * This helps adding a mirror texture on the ground.
  96686. */
  96687. _this.reflectionFresnel = false;
  96688. /**
  96689. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96690. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96691. */
  96692. _this.reflectionFalloffDistance = 0.0;
  96693. /**
  96694. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96695. */
  96696. _this.reflectionAmount = 1.0;
  96697. /**
  96698. * This specifies the weight of the reflection at grazing angle.
  96699. */
  96700. _this.reflectionReflectance0 = 0.05;
  96701. /**
  96702. * This specifies the weight of the reflection at a perpendicular point of view.
  96703. */
  96704. _this.reflectionReflectance90 = 0.5;
  96705. /**
  96706. * Helps to directly use the maps channels instead of their level.
  96707. */
  96708. _this.useRGBColor = true;
  96709. /**
  96710. * This helps reducing the banding effect that could occur on the background.
  96711. */
  96712. _this.enableNoise = false;
  96713. _this._fovMultiplier = 1.0;
  96714. /**
  96715. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96716. */
  96717. _this.useEquirectangularFOV = false;
  96718. _this._maxSimultaneousLights = 4;
  96719. /**
  96720. * Number of Simultaneous lights allowed on the material.
  96721. */
  96722. _this.maxSimultaneousLights = 4;
  96723. /**
  96724. * Keep track of the image processing observer to allow dispose and replace.
  96725. */
  96726. _this._imageProcessingObserver = null;
  96727. /**
  96728. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96729. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96730. */
  96731. _this.switchToBGR = false;
  96732. // Temp values kept as cache in the material.
  96733. _this._renderTargets = new BABYLON.SmartArray(16);
  96734. _this._reflectionControls = BABYLON.Vector4.Zero();
  96735. _this._white = BABYLON.Color3.White();
  96736. _this._primaryShadowColor = BABYLON.Color3.Black();
  96737. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96738. // Setup the default processing configuration to the scene.
  96739. _this._attachImageProcessingConfiguration(null);
  96740. _this.getRenderTargetTextures = function () {
  96741. _this._renderTargets.reset();
  96742. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96743. _this._renderTargets.push(_this._diffuseTexture);
  96744. }
  96745. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96746. _this._renderTargets.push(_this._reflectionTexture);
  96747. }
  96748. return _this._renderTargets;
  96749. };
  96750. return _this;
  96751. }
  96752. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96753. /**
  96754. * Experimental Internal Use Only.
  96755. *
  96756. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96757. * This acts as a helper to set the primary color to a more "human friendly" value.
  96758. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96759. * output color as close as possible from the chosen value.
  96760. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96761. * part of lighting setup.)
  96762. */
  96763. get: function () {
  96764. return this.__perceptualColor;
  96765. },
  96766. set: function (value) {
  96767. this.__perceptualColor = value;
  96768. this._computePrimaryColorFromPerceptualColor();
  96769. this._markAllSubMeshesAsLightsDirty();
  96770. },
  96771. enumerable: true,
  96772. configurable: true
  96773. });
  96774. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96775. /**
  96776. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96777. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96778. */
  96779. get: function () {
  96780. return this._primaryColorShadowLevel;
  96781. },
  96782. set: function (value) {
  96783. this._primaryColorShadowLevel = value;
  96784. this._computePrimaryColors();
  96785. this._markAllSubMeshesAsLightsDirty();
  96786. },
  96787. enumerable: true,
  96788. configurable: true
  96789. });
  96790. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96791. /**
  96792. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96793. * The primary color is used at the level chosen to define what the white area would look.
  96794. */
  96795. get: function () {
  96796. return this._primaryColorHighlightLevel;
  96797. },
  96798. set: function (value) {
  96799. this._primaryColorHighlightLevel = value;
  96800. this._computePrimaryColors();
  96801. this._markAllSubMeshesAsLightsDirty();
  96802. },
  96803. enumerable: true,
  96804. configurable: true
  96805. });
  96806. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96807. /**
  96808. * Sets the reflection reflectance fresnel values according to the default standard
  96809. * empirically know to work well :-)
  96810. */
  96811. set: function (value) {
  96812. var reflectionWeight = value;
  96813. if (reflectionWeight < 0.5) {
  96814. reflectionWeight = reflectionWeight * 2.0;
  96815. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96816. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96817. }
  96818. else {
  96819. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96820. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96821. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96822. }
  96823. },
  96824. enumerable: true,
  96825. configurable: true
  96826. });
  96827. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96828. /**
  96829. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96830. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96831. * Recommended to be keep at 1.0 except for special cases.
  96832. */
  96833. get: function () {
  96834. return this._fovMultiplier;
  96835. },
  96836. set: function (value) {
  96837. if (isNaN(value)) {
  96838. value = 1.0;
  96839. }
  96840. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96841. },
  96842. enumerable: true,
  96843. configurable: true
  96844. });
  96845. /**
  96846. * Attaches a new image processing configuration to the PBR Material.
  96847. * @param configuration (if null the scene configuration will be use)
  96848. */
  96849. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96850. var _this = this;
  96851. if (configuration === this._imageProcessingConfiguration) {
  96852. return;
  96853. }
  96854. // Detaches observer.
  96855. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96856. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96857. }
  96858. // Pick the scene configuration if needed.
  96859. if (!configuration) {
  96860. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96861. }
  96862. else {
  96863. this._imageProcessingConfiguration = configuration;
  96864. }
  96865. // Attaches observer.
  96866. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96867. _this._computePrimaryColorFromPerceptualColor();
  96868. _this._markAllSubMeshesAsImageProcessingDirty();
  96869. });
  96870. };
  96871. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96872. /**
  96873. * Gets the image processing configuration used either in this material.
  96874. */
  96875. get: function () {
  96876. return this._imageProcessingConfiguration;
  96877. },
  96878. /**
  96879. * Sets the Default image processing configuration used either in the this material.
  96880. *
  96881. * If sets to null, the scene one is in use.
  96882. */
  96883. set: function (value) {
  96884. this._attachImageProcessingConfiguration(value);
  96885. // Ensure the effect will be rebuilt.
  96886. this._markAllSubMeshesAsTexturesDirty();
  96887. },
  96888. enumerable: true,
  96889. configurable: true
  96890. });
  96891. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96892. /**
  96893. * Gets wether the color curves effect is enabled.
  96894. */
  96895. get: function () {
  96896. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96897. },
  96898. /**
  96899. * Sets wether the color curves effect is enabled.
  96900. */
  96901. set: function (value) {
  96902. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96903. },
  96904. enumerable: true,
  96905. configurable: true
  96906. });
  96907. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96908. /**
  96909. * Gets wether the color grading effect is enabled.
  96910. */
  96911. get: function () {
  96912. return this.imageProcessingConfiguration.colorGradingEnabled;
  96913. },
  96914. /**
  96915. * Gets wether the color grading effect is enabled.
  96916. */
  96917. set: function (value) {
  96918. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96919. },
  96920. enumerable: true,
  96921. configurable: true
  96922. });
  96923. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96924. /**
  96925. * Gets wether tonemapping is enabled or not.
  96926. */
  96927. get: function () {
  96928. return this._imageProcessingConfiguration.toneMappingEnabled;
  96929. },
  96930. /**
  96931. * Sets wether tonemapping is enabled or not
  96932. */
  96933. set: function (value) {
  96934. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96935. },
  96936. enumerable: true,
  96937. configurable: true
  96938. });
  96939. ;
  96940. ;
  96941. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96942. /**
  96943. * The camera exposure used on this material.
  96944. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96945. * This corresponds to a photographic exposure.
  96946. */
  96947. get: function () {
  96948. return this._imageProcessingConfiguration.exposure;
  96949. },
  96950. /**
  96951. * The camera exposure used on this material.
  96952. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96953. * This corresponds to a photographic exposure.
  96954. */
  96955. set: function (value) {
  96956. this._imageProcessingConfiguration.exposure = value;
  96957. },
  96958. enumerable: true,
  96959. configurable: true
  96960. });
  96961. ;
  96962. ;
  96963. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96964. /**
  96965. * Gets The camera contrast used on this material.
  96966. */
  96967. get: function () {
  96968. return this._imageProcessingConfiguration.contrast;
  96969. },
  96970. /**
  96971. * Sets The camera contrast used on this material.
  96972. */
  96973. set: function (value) {
  96974. this._imageProcessingConfiguration.contrast = value;
  96975. },
  96976. enumerable: true,
  96977. configurable: true
  96978. });
  96979. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96980. /**
  96981. * Gets the Color Grading 2D Lookup Texture.
  96982. */
  96983. get: function () {
  96984. return this._imageProcessingConfiguration.colorGradingTexture;
  96985. },
  96986. /**
  96987. * Sets the Color Grading 2D Lookup Texture.
  96988. */
  96989. set: function (value) {
  96990. this.imageProcessingConfiguration.colorGradingTexture = value;
  96991. },
  96992. enumerable: true,
  96993. configurable: true
  96994. });
  96995. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96996. /**
  96997. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96998. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96999. * 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;
  97000. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  97001. */
  97002. get: function () {
  97003. return this.imageProcessingConfiguration.colorCurves;
  97004. },
  97005. /**
  97006. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  97007. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  97008. * 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;
  97009. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  97010. */
  97011. set: function (value) {
  97012. this.imageProcessingConfiguration.colorCurves = value;
  97013. },
  97014. enumerable: true,
  97015. configurable: true
  97016. });
  97017. /**
  97018. * The entire material has been created in order to prevent overdraw.
  97019. * @returns false
  97020. */
  97021. BackgroundMaterial.prototype.needAlphaTesting = function () {
  97022. return true;
  97023. };
  97024. /**
  97025. * The entire material has been created in order to prevent overdraw.
  97026. * @returns true if blending is enable
  97027. */
  97028. BackgroundMaterial.prototype.needAlphaBlending = function () {
  97029. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  97030. };
  97031. /**
  97032. * Checks wether the material is ready to be rendered for a given mesh.
  97033. * @param mesh The mesh to render
  97034. * @param subMesh The submesh to check against
  97035. * @param useInstances Specify wether or not the material is used with instances
  97036. * @returns true if all the dependencies are ready (Textures, Effects...)
  97037. */
  97038. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  97039. var _this = this;
  97040. if (useInstances === void 0) { useInstances = false; }
  97041. if (subMesh.effect && this.isFrozen) {
  97042. if (this._wasPreviouslyReady) {
  97043. return true;
  97044. }
  97045. }
  97046. if (!subMesh._materialDefines) {
  97047. subMesh._materialDefines = new BackgroundMaterialDefines();
  97048. }
  97049. var scene = this.getScene();
  97050. var defines = subMesh._materialDefines;
  97051. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  97052. if (defines._renderId === scene.getRenderId()) {
  97053. return true;
  97054. }
  97055. }
  97056. var engine = scene.getEngine();
  97057. // Lights
  97058. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  97059. defines._needNormals = true;
  97060. // Textures
  97061. if (defines._areTexturesDirty) {
  97062. defines._needUVs = false;
  97063. if (scene.texturesEnabled) {
  97064. if (scene.getEngine().getCaps().textureLOD) {
  97065. defines.TEXTURELODSUPPORT = true;
  97066. }
  97067. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97068. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  97069. return false;
  97070. }
  97071. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  97072. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  97073. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  97074. defines.OPACITYFRESNEL = this._opacityFresnel;
  97075. }
  97076. else {
  97077. defines.DIFFUSE = false;
  97078. defines.DIFFUSEHASALPHA = false;
  97079. defines.GAMMADIFFUSE = false;
  97080. defines.OPACITYFRESNEL = false;
  97081. }
  97082. var reflectionTexture = this._reflectionTexture;
  97083. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97084. if (!reflectionTexture.isReadyOrNotBlocking()) {
  97085. return false;
  97086. }
  97087. defines.REFLECTION = true;
  97088. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  97089. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  97090. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  97091. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  97092. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  97093. defines.REFLECTIONBGR = this.switchToBGR;
  97094. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  97095. defines.INVERTCUBICMAP = true;
  97096. }
  97097. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  97098. switch (reflectionTexture.coordinatesMode) {
  97099. case BABYLON.Texture.EXPLICIT_MODE:
  97100. defines.REFLECTIONMAP_EXPLICIT = true;
  97101. break;
  97102. case BABYLON.Texture.PLANAR_MODE:
  97103. defines.REFLECTIONMAP_PLANAR = true;
  97104. break;
  97105. case BABYLON.Texture.PROJECTION_MODE:
  97106. defines.REFLECTIONMAP_PROJECTION = true;
  97107. break;
  97108. case BABYLON.Texture.SKYBOX_MODE:
  97109. defines.REFLECTIONMAP_SKYBOX = true;
  97110. break;
  97111. case BABYLON.Texture.SPHERICAL_MODE:
  97112. defines.REFLECTIONMAP_SPHERICAL = true;
  97113. break;
  97114. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  97115. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  97116. break;
  97117. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  97118. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  97119. break;
  97120. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  97121. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  97122. break;
  97123. case BABYLON.Texture.CUBIC_MODE:
  97124. case BABYLON.Texture.INVCUBIC_MODE:
  97125. default:
  97126. defines.REFLECTIONMAP_CUBIC = true;
  97127. break;
  97128. }
  97129. if (this.reflectionFresnel) {
  97130. defines.REFLECTIONFRESNEL = true;
  97131. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  97132. this._reflectionControls.x = this.reflectionAmount;
  97133. this._reflectionControls.y = this.reflectionReflectance0;
  97134. this._reflectionControls.z = this.reflectionReflectance90;
  97135. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  97136. }
  97137. else {
  97138. defines.REFLECTIONFRESNEL = false;
  97139. defines.REFLECTIONFALLOFF = false;
  97140. }
  97141. }
  97142. else {
  97143. defines.REFLECTION = false;
  97144. defines.REFLECTIONFRESNEL = false;
  97145. defines.REFLECTIONFALLOFF = false;
  97146. defines.REFLECTIONBLUR = false;
  97147. defines.REFLECTIONMAP_3D = false;
  97148. defines.REFLECTIONMAP_SPHERICAL = false;
  97149. defines.REFLECTIONMAP_PLANAR = false;
  97150. defines.REFLECTIONMAP_CUBIC = false;
  97151. defines.REFLECTIONMAP_PROJECTION = false;
  97152. defines.REFLECTIONMAP_SKYBOX = false;
  97153. defines.REFLECTIONMAP_EXPLICIT = false;
  97154. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  97155. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  97156. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  97157. defines.INVERTCUBICMAP = false;
  97158. defines.REFLECTIONMAP_OPPOSITEZ = false;
  97159. defines.LODINREFLECTIONALPHA = false;
  97160. defines.GAMMAREFLECTION = false;
  97161. }
  97162. }
  97163. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  97164. defines.USERGBCOLOR = this._useRGBColor;
  97165. defines.NOISE = this._enableNoise;
  97166. }
  97167. if (defines._areLightsDirty) {
  97168. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  97169. }
  97170. if (defines._areImageProcessingDirty) {
  97171. if (!this._imageProcessingConfiguration.isReady()) {
  97172. return false;
  97173. }
  97174. this._imageProcessingConfiguration.prepareDefines(defines);
  97175. }
  97176. // Misc.
  97177. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  97178. // Values that need to be evaluated on every frame
  97179. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  97180. // Attribs
  97181. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  97182. if (mesh) {
  97183. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  97184. mesh.createNormals(true);
  97185. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  97186. }
  97187. }
  97188. }
  97189. // Get correct effect
  97190. if (defines.isDirty) {
  97191. defines.markAsProcessed();
  97192. scene.resetCachedMaterial();
  97193. // Fallbacks
  97194. var fallbacks = new BABYLON.EffectFallbacks();
  97195. if (defines.FOG) {
  97196. fallbacks.addFallback(0, "FOG");
  97197. }
  97198. if (defines.POINTSIZE) {
  97199. fallbacks.addFallback(1, "POINTSIZE");
  97200. }
  97201. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  97202. if (defines.NUM_BONE_INFLUENCERS > 0) {
  97203. fallbacks.addCPUSkinningFallback(0, mesh);
  97204. }
  97205. //Attributes
  97206. var attribs = [BABYLON.VertexBuffer.PositionKind];
  97207. if (defines.NORMAL) {
  97208. attribs.push(BABYLON.VertexBuffer.NormalKind);
  97209. }
  97210. if (defines.UV1) {
  97211. attribs.push(BABYLON.VertexBuffer.UVKind);
  97212. }
  97213. if (defines.UV2) {
  97214. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  97215. }
  97216. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  97217. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  97218. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  97219. "vFogInfos", "vFogColor", "pointSize",
  97220. "vClipPlane", "mBones",
  97221. "vPrimaryColor", "vPrimaryColorShadow",
  97222. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  97223. "shadowLevel", "alpha",
  97224. "vBackgroundCenter", "vReflectionControl",
  97225. "vDiffuseInfos", "diffuseMatrix",
  97226. ];
  97227. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  97228. var uniformBuffers = ["Material", "Scene"];
  97229. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  97230. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  97231. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  97232. uniformsNames: uniforms,
  97233. uniformBuffersNames: uniformBuffers,
  97234. samplers: samplers,
  97235. defines: defines,
  97236. maxSimultaneousLights: this._maxSimultaneousLights
  97237. });
  97238. var onCompiled = function (effect) {
  97239. if (_this.onCompiled) {
  97240. _this.onCompiled(effect);
  97241. }
  97242. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  97243. };
  97244. var join = defines.toString();
  97245. subMesh.setEffect(scene.getEngine().createEffect("background", {
  97246. attributes: attribs,
  97247. uniformsNames: uniforms,
  97248. uniformBuffersNames: uniformBuffers,
  97249. samplers: samplers,
  97250. defines: join,
  97251. fallbacks: fallbacks,
  97252. onCompiled: onCompiled,
  97253. onError: this.onError,
  97254. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  97255. }, engine), defines);
  97256. this.buildUniformLayout();
  97257. }
  97258. if (!subMesh.effect || !subMesh.effect.isReady()) {
  97259. return false;
  97260. }
  97261. defines._renderId = scene.getRenderId();
  97262. this._wasPreviouslyReady = true;
  97263. return true;
  97264. };
  97265. /**
  97266. * Compute the primary color according to the chosen perceptual color.
  97267. */
  97268. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  97269. if (!this.__perceptualColor) {
  97270. return;
  97271. }
  97272. this._primaryColor.copyFrom(this.__perceptualColor);
  97273. // Revert gamma space.
  97274. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  97275. // Revert image processing configuration.
  97276. if (this._imageProcessingConfiguration) {
  97277. // Revert Exposure.
  97278. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  97279. }
  97280. this._computePrimaryColors();
  97281. };
  97282. /**
  97283. * Compute the highlights and shadow colors according to their chosen levels.
  97284. */
  97285. BackgroundMaterial.prototype._computePrimaryColors = function () {
  97286. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  97287. return;
  97288. }
  97289. // Find the highlight color based on the configuration.
  97290. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  97291. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  97292. // Find the shadow color based on the configuration.
  97293. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  97294. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  97295. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  97296. };
  97297. /**
  97298. * Build the uniform buffer used in the material.
  97299. */
  97300. BackgroundMaterial.prototype.buildUniformLayout = function () {
  97301. // Order is important !
  97302. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  97303. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  97304. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  97305. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  97306. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  97307. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  97308. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  97309. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  97310. this._uniformBuffer.addUniform("pointSize", 1);
  97311. this._uniformBuffer.addUniform("shadowLevel", 1);
  97312. this._uniformBuffer.addUniform("alpha", 1);
  97313. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  97314. this._uniformBuffer.addUniform("vReflectionControl", 4);
  97315. this._uniformBuffer.create();
  97316. };
  97317. /**
  97318. * Unbind the material.
  97319. */
  97320. BackgroundMaterial.prototype.unbind = function () {
  97321. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  97322. this._uniformBuffer.setTexture("diffuseSampler", null);
  97323. }
  97324. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  97325. this._uniformBuffer.setTexture("reflectionSampler", null);
  97326. }
  97327. _super.prototype.unbind.call(this);
  97328. };
  97329. /**
  97330. * Bind only the world matrix to the material.
  97331. * @param world The world matrix to bind.
  97332. */
  97333. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  97334. this._activeEffect.setMatrix("world", world);
  97335. };
  97336. /**
  97337. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  97338. * @param world The world matrix to bind.
  97339. * @param subMesh The submesh to bind for.
  97340. */
  97341. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  97342. var scene = this.getScene();
  97343. var defines = subMesh._materialDefines;
  97344. if (!defines) {
  97345. return;
  97346. }
  97347. var effect = subMesh.effect;
  97348. if (!effect) {
  97349. return;
  97350. }
  97351. this._activeEffect = effect;
  97352. // Matrices
  97353. this.bindOnlyWorldMatrix(world);
  97354. // Bones
  97355. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  97356. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  97357. if (mustRebind) {
  97358. this._uniformBuffer.bindToEffect(effect, "Material");
  97359. this.bindViewProjection(effect);
  97360. var reflectionTexture = this._reflectionTexture;
  97361. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  97362. // Texture uniforms
  97363. if (scene.texturesEnabled) {
  97364. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97365. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  97366. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  97367. }
  97368. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97369. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  97370. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  97371. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  97372. }
  97373. }
  97374. if (this.shadowLevel > 0) {
  97375. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  97376. }
  97377. this._uniformBuffer.updateFloat("alpha", this.alpha);
  97378. // Point size
  97379. if (this.pointsCloud) {
  97380. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  97381. }
  97382. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  97383. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  97384. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  97385. }
  97386. else {
  97387. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  97388. }
  97389. }
  97390. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  97391. // Textures
  97392. if (scene.texturesEnabled) {
  97393. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97394. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  97395. }
  97396. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97397. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  97398. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97399. }
  97400. else if (!defines.REFLECTIONBLUR) {
  97401. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97402. }
  97403. else {
  97404. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  97405. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  97406. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  97407. }
  97408. if (defines.REFLECTIONFRESNEL) {
  97409. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  97410. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  97411. }
  97412. }
  97413. }
  97414. // Clip plane
  97415. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  97416. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  97417. }
  97418. if (mustRebind || !this.isFrozen) {
  97419. if (scene.lightsEnabled) {
  97420. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  97421. }
  97422. // View
  97423. this.bindView(effect);
  97424. // Fog
  97425. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  97426. // image processing
  97427. this._imageProcessingConfiguration.bind(this._activeEffect);
  97428. }
  97429. this._uniformBuffer.update();
  97430. this._afterBind(mesh);
  97431. };
  97432. /**
  97433. * Dispose the material.
  97434. * @param forceDisposeEffect Force disposal of the associated effect.
  97435. * @param forceDisposeTextures Force disposal of the associated textures.
  97436. */
  97437. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  97438. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  97439. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  97440. if (forceDisposeTextures) {
  97441. if (this.diffuseTexture) {
  97442. this.diffuseTexture.dispose();
  97443. }
  97444. if (this.reflectionTexture) {
  97445. this.reflectionTexture.dispose();
  97446. }
  97447. }
  97448. this._renderTargets.dispose();
  97449. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97450. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97451. }
  97452. _super.prototype.dispose.call(this, forceDisposeEffect);
  97453. };
  97454. /**
  97455. * Clones the material.
  97456. * @param name The cloned name.
  97457. * @returns The cloned material.
  97458. */
  97459. BackgroundMaterial.prototype.clone = function (name) {
  97460. var _this = this;
  97461. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  97462. };
  97463. /**
  97464. * Serializes the current material to its JSON representation.
  97465. * @returns The JSON representation.
  97466. */
  97467. BackgroundMaterial.prototype.serialize = function () {
  97468. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97469. serializationObject.customType = "BABYLON.BackgroundMaterial";
  97470. return serializationObject;
  97471. };
  97472. /**
  97473. * Gets the class name of the material
  97474. * @returns "BackgroundMaterial"
  97475. */
  97476. BackgroundMaterial.prototype.getClassName = function () {
  97477. return "BackgroundMaterial";
  97478. };
  97479. /**
  97480. * Parse a JSON input to create back a background material.
  97481. * @param source The JSON data to parse
  97482. * @param scene The scene to create the parsed material in
  97483. * @param rootUrl The root url of the assets the material depends upon
  97484. * @returns the instantiated BackgroundMaterial.
  97485. */
  97486. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  97487. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  97488. };
  97489. /**
  97490. * Standard reflectance value at parallel view angle.
  97491. */
  97492. BackgroundMaterial.StandardReflectance0 = 0.05;
  97493. /**
  97494. * Standard reflectance value at grazing angle.
  97495. */
  97496. BackgroundMaterial.StandardReflectance90 = 0.5;
  97497. __decorate([
  97498. BABYLON.serializeAsColor3()
  97499. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  97500. __decorate([
  97501. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97502. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  97503. __decorate([
  97504. BABYLON.serializeAsColor3()
  97505. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  97506. __decorate([
  97507. BABYLON.serialize()
  97508. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  97509. __decorate([
  97510. BABYLON.serialize()
  97511. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  97512. __decorate([
  97513. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97514. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  97515. __decorate([
  97516. BABYLON.serializeAsTexture()
  97517. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  97518. __decorate([
  97519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97520. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  97521. __decorate([
  97522. BABYLON.serialize()
  97523. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  97524. __decorate([
  97525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97526. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  97527. __decorate([
  97528. BABYLON.serializeAsTexture()
  97529. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  97530. __decorate([
  97531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97532. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  97533. __decorate([
  97534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97535. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  97536. __decorate([
  97537. BABYLON.serialize()
  97538. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  97539. __decorate([
  97540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97541. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  97542. __decorate([
  97543. BABYLON.serializeAsVector3()
  97544. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  97545. __decorate([
  97546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97547. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  97548. __decorate([
  97549. BABYLON.serialize()
  97550. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  97551. __decorate([
  97552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97553. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  97554. __decorate([
  97555. BABYLON.serialize()
  97556. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  97557. __decorate([
  97558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97559. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  97560. __decorate([
  97561. BABYLON.serialize()
  97562. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  97563. __decorate([
  97564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97565. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  97566. __decorate([
  97567. BABYLON.serialize()
  97568. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  97569. __decorate([
  97570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97571. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  97572. __decorate([
  97573. BABYLON.serialize()
  97574. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  97575. __decorate([
  97576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97577. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  97578. __decorate([
  97579. BABYLON.serialize()
  97580. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  97581. __decorate([
  97582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97583. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  97584. __decorate([
  97585. BABYLON.serialize()
  97586. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  97587. __decorate([
  97588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97589. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  97590. __decorate([
  97591. BABYLON.serialize()
  97592. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  97593. __decorate([
  97594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97595. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  97596. __decorate([
  97597. BABYLON.serialize()
  97598. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  97599. __decorate([
  97600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97601. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  97602. __decorate([
  97603. BABYLON.serializeAsImageProcessingConfiguration()
  97604. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  97605. return BackgroundMaterial;
  97606. }(BABYLON.PushMaterial));
  97607. BABYLON.BackgroundMaterial = BackgroundMaterial;
  97608. })(BABYLON || (BABYLON = {}));
  97609. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  97610. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97611. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97612. s = arguments[i];
  97613. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97614. t[p] = s[p];
  97615. }
  97616. return t;
  97617. };
  97618. var BABYLON;
  97619. (function (BABYLON) {
  97620. /**
  97621. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97622. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97623. * It also helps with the default setup of your imageProcessing configuration.
  97624. */
  97625. var EnvironmentHelper = /** @class */ (function () {
  97626. /**
  97627. * constructor
  97628. * @param options
  97629. * @param scene The scene to add the material to
  97630. */
  97631. function EnvironmentHelper(options, scene) {
  97632. var _this = this;
  97633. this._errorHandler = function (message, exception) {
  97634. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97635. };
  97636. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97637. this._scene = scene;
  97638. this.onErrorObservable = new BABYLON.Observable();
  97639. this._setupBackground();
  97640. this._setupImageProcessing();
  97641. }
  97642. /**
  97643. * Creates the default options for the helper.
  97644. */
  97645. EnvironmentHelper._getDefaultOptions = function () {
  97646. return {
  97647. createGround: true,
  97648. groundSize: 15,
  97649. groundTexture: this._groundTextureCDNUrl,
  97650. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97651. groundOpacity: 0.9,
  97652. enableGroundShadow: true,
  97653. groundShadowLevel: 0.5,
  97654. enableGroundMirror: false,
  97655. groundMirrorSizeRatio: 0.3,
  97656. groundMirrorBlurKernel: 64,
  97657. groundMirrorAmount: 1,
  97658. groundMirrorFresnelWeight: 1,
  97659. groundMirrorFallOffDistance: 0,
  97660. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97661. groundYBias: 0.00001,
  97662. createSkybox: true,
  97663. skyboxSize: 20,
  97664. skyboxTexture: this._skyboxTextureCDNUrl,
  97665. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97666. backgroundYRotation: 0,
  97667. sizeAuto: true,
  97668. rootPosition: BABYLON.Vector3.Zero(),
  97669. setupImageProcessing: true,
  97670. environmentTexture: this._environmentTextureCDNUrl,
  97671. cameraExposure: 0.8,
  97672. cameraContrast: 1.2,
  97673. toneMappingEnabled: true,
  97674. };
  97675. };
  97676. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97677. /**
  97678. * Gets the root mesh created by the helper.
  97679. */
  97680. get: function () {
  97681. return this._rootMesh;
  97682. },
  97683. enumerable: true,
  97684. configurable: true
  97685. });
  97686. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97687. /**
  97688. * Gets the skybox created by the helper.
  97689. */
  97690. get: function () {
  97691. return this._skybox;
  97692. },
  97693. enumerable: true,
  97694. configurable: true
  97695. });
  97696. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97697. /**
  97698. * Gets the skybox texture created by the helper.
  97699. */
  97700. get: function () {
  97701. return this._skyboxTexture;
  97702. },
  97703. enumerable: true,
  97704. configurable: true
  97705. });
  97706. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97707. /**
  97708. * Gets the skybox material created by the helper.
  97709. */
  97710. get: function () {
  97711. return this._skyboxMaterial;
  97712. },
  97713. enumerable: true,
  97714. configurable: true
  97715. });
  97716. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97717. /**
  97718. * Gets the ground mesh created by the helper.
  97719. */
  97720. get: function () {
  97721. return this._ground;
  97722. },
  97723. enumerable: true,
  97724. configurable: true
  97725. });
  97726. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97727. /**
  97728. * Gets the ground texture created by the helper.
  97729. */
  97730. get: function () {
  97731. return this._groundTexture;
  97732. },
  97733. enumerable: true,
  97734. configurable: true
  97735. });
  97736. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97737. /**
  97738. * Gets the ground mirror created by the helper.
  97739. */
  97740. get: function () {
  97741. return this._groundMirror;
  97742. },
  97743. enumerable: true,
  97744. configurable: true
  97745. });
  97746. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97747. /**
  97748. * Gets the ground mirror render list to helps pushing the meshes
  97749. * you wish in the ground reflection.
  97750. */
  97751. get: function () {
  97752. if (this._groundMirror) {
  97753. return this._groundMirror.renderList;
  97754. }
  97755. return null;
  97756. },
  97757. enumerable: true,
  97758. configurable: true
  97759. });
  97760. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97761. /**
  97762. * Gets the ground material created by the helper.
  97763. */
  97764. get: function () {
  97765. return this._groundMaterial;
  97766. },
  97767. enumerable: true,
  97768. configurable: true
  97769. });
  97770. /**
  97771. * Updates the background according to the new options
  97772. * @param options
  97773. */
  97774. EnvironmentHelper.prototype.updateOptions = function (options) {
  97775. var newOptions = __assign({}, this._options, options);
  97776. if (this._ground && !newOptions.createGround) {
  97777. this._ground.dispose();
  97778. this._ground = null;
  97779. }
  97780. if (this._groundMaterial && !newOptions.createGround) {
  97781. this._groundMaterial.dispose();
  97782. this._groundMaterial = null;
  97783. }
  97784. if (this._groundTexture) {
  97785. if (this._options.groundTexture != newOptions.groundTexture) {
  97786. this._groundTexture.dispose();
  97787. this._groundTexture = null;
  97788. }
  97789. }
  97790. if (this._skybox && !newOptions.createSkybox) {
  97791. this._skybox.dispose();
  97792. this._skybox = null;
  97793. }
  97794. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97795. this._skyboxMaterial.dispose();
  97796. this._skyboxMaterial = null;
  97797. }
  97798. if (this._skyboxTexture) {
  97799. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97800. this._skyboxTexture.dispose();
  97801. this._skyboxTexture = null;
  97802. }
  97803. }
  97804. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97805. this._groundMirror.dispose();
  97806. this._groundMirror = null;
  97807. }
  97808. if (this._scene.environmentTexture) {
  97809. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97810. this._scene.environmentTexture.dispose();
  97811. }
  97812. }
  97813. this._options = newOptions;
  97814. this._setupBackground();
  97815. this._setupImageProcessing();
  97816. };
  97817. /**
  97818. * Sets the primary color of all the available elements.
  97819. * @param color the main color to affect to the ground and the background
  97820. */
  97821. EnvironmentHelper.prototype.setMainColor = function (color) {
  97822. if (this.groundMaterial) {
  97823. this.groundMaterial.primaryColor = color;
  97824. }
  97825. if (this.skyboxMaterial) {
  97826. this.skyboxMaterial.primaryColor = color;
  97827. }
  97828. if (this.groundMirror) {
  97829. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97830. }
  97831. };
  97832. /**
  97833. * Setup the image processing according to the specified options.
  97834. */
  97835. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97836. if (this._options.setupImageProcessing) {
  97837. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97838. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97839. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97840. this._setupEnvironmentTexture();
  97841. }
  97842. };
  97843. /**
  97844. * Setup the environment texture according to the specified options.
  97845. */
  97846. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97847. if (this._scene.environmentTexture) {
  97848. return;
  97849. }
  97850. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97851. this._scene.environmentTexture = this._options.environmentTexture;
  97852. return;
  97853. }
  97854. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97855. this._scene.environmentTexture = environmentTexture;
  97856. };
  97857. /**
  97858. * Setup the background according to the specified options.
  97859. */
  97860. EnvironmentHelper.prototype._setupBackground = function () {
  97861. if (!this._rootMesh) {
  97862. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97863. }
  97864. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97865. var sceneSize = this._getSceneSize();
  97866. if (this._options.createGround) {
  97867. this._setupGround(sceneSize);
  97868. this._setupGroundMaterial();
  97869. this._setupGroundDiffuseTexture();
  97870. if (this._options.enableGroundMirror) {
  97871. this._setupGroundMirrorTexture(sceneSize);
  97872. }
  97873. this._setupMirrorInGroundMaterial();
  97874. }
  97875. if (this._options.createSkybox) {
  97876. this._setupSkybox(sceneSize);
  97877. this._setupSkyboxMaterial();
  97878. this._setupSkyboxReflectionTexture();
  97879. }
  97880. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97881. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97882. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97883. };
  97884. /**
  97885. * Get the scene sizes according to the setup.
  97886. */
  97887. EnvironmentHelper.prototype._getSceneSize = function () {
  97888. var _this = this;
  97889. var groundSize = this._options.groundSize;
  97890. var skyboxSize = this._options.skyboxSize;
  97891. var rootPosition = this._options.rootPosition;
  97892. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97893. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97894. }
  97895. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97896. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97897. });
  97898. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97899. if (this._options.sizeAuto) {
  97900. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97901. this._scene.activeCamera.upperRadiusLimit) {
  97902. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97903. skyboxSize = groundSize;
  97904. }
  97905. var sceneDiagonalLenght = sceneDiagonal.length();
  97906. if (sceneDiagonalLenght > groundSize) {
  97907. groundSize = sceneDiagonalLenght * 2;
  97908. skyboxSize = groundSize;
  97909. }
  97910. // 10 % bigger.
  97911. groundSize *= 1.1;
  97912. skyboxSize *= 1.5;
  97913. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97914. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97915. }
  97916. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97917. };
  97918. /**
  97919. * Setup the ground according to the specified options.
  97920. */
  97921. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97922. var _this = this;
  97923. if (!this._ground) {
  97924. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97925. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97926. this._ground.parent = this._rootMesh;
  97927. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97928. }
  97929. this._ground.receiveShadows = this._options.enableGroundShadow;
  97930. };
  97931. /**
  97932. * Setup the ground material according to the specified options.
  97933. */
  97934. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97935. if (!this._groundMaterial) {
  97936. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97937. }
  97938. this._groundMaterial.alpha = this._options.groundOpacity;
  97939. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97940. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97941. this._groundMaterial.primaryColor = this._options.groundColor;
  97942. this._groundMaterial.useRGBColor = false;
  97943. this._groundMaterial.enableNoise = true;
  97944. if (this._ground) {
  97945. this._ground.material = this._groundMaterial;
  97946. }
  97947. };
  97948. /**
  97949. * Setup the ground diffuse texture according to the specified options.
  97950. */
  97951. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97952. if (!this._groundMaterial) {
  97953. return;
  97954. }
  97955. if (this._groundTexture) {
  97956. return;
  97957. }
  97958. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97959. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97960. return;
  97961. }
  97962. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97963. diffuseTexture.gammaSpace = false;
  97964. diffuseTexture.hasAlpha = true;
  97965. this._groundMaterial.diffuseTexture = diffuseTexture;
  97966. };
  97967. /**
  97968. * Setup the ground mirror texture according to the specified options.
  97969. */
  97970. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97971. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97972. if (!this._groundMirror) {
  97973. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97974. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97975. this._groundMirror.anisotropicFilteringLevel = 1;
  97976. this._groundMirror.wrapU = wrapping;
  97977. this._groundMirror.wrapV = wrapping;
  97978. this._groundMirror.gammaSpace = false;
  97979. if (this._groundMirror.renderList) {
  97980. for (var i = 0; i < this._scene.meshes.length; i++) {
  97981. var mesh = this._scene.meshes[i];
  97982. if (mesh !== this._ground &&
  97983. mesh !== this._skybox &&
  97984. mesh !== this._rootMesh) {
  97985. this._groundMirror.renderList.push(mesh);
  97986. }
  97987. }
  97988. }
  97989. }
  97990. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97991. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97992. };
  97993. /**
  97994. * Setup the ground to receive the mirror texture.
  97995. */
  97996. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97997. if (this._groundMaterial) {
  97998. this._groundMaterial.reflectionTexture = this._groundMirror;
  97999. this._groundMaterial.reflectionFresnel = true;
  98000. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  98001. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  98002. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  98003. }
  98004. };
  98005. /**
  98006. * Setup the skybox according to the specified options.
  98007. */
  98008. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  98009. var _this = this;
  98010. if (!this._skybox) {
  98011. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  98012. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  98013. }
  98014. this._skybox.parent = this._rootMesh;
  98015. };
  98016. /**
  98017. * Setup the skybox material according to the specified options.
  98018. */
  98019. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  98020. if (!this._skybox) {
  98021. return;
  98022. }
  98023. if (!this._skyboxMaterial) {
  98024. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  98025. }
  98026. this._skyboxMaterial.useRGBColor = false;
  98027. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  98028. this._skyboxMaterial.enableNoise = true;
  98029. this._skybox.material = this._skyboxMaterial;
  98030. };
  98031. /**
  98032. * Setup the skybox reflection texture according to the specified options.
  98033. */
  98034. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  98035. if (!this._skyboxMaterial) {
  98036. return;
  98037. }
  98038. if (this._skyboxTexture) {
  98039. return;
  98040. }
  98041. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  98042. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  98043. return;
  98044. }
  98045. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  98046. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  98047. this._skyboxTexture.gammaSpace = false;
  98048. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  98049. };
  98050. /**
  98051. * Dispose all the elements created by the Helper.
  98052. */
  98053. EnvironmentHelper.prototype.dispose = function () {
  98054. if (this._groundMaterial) {
  98055. this._groundMaterial.dispose(true, true);
  98056. }
  98057. if (this._skyboxMaterial) {
  98058. this._skyboxMaterial.dispose(true, true);
  98059. }
  98060. this._rootMesh.dispose(false);
  98061. };
  98062. /**
  98063. * Default ground texture URL.
  98064. */
  98065. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  98066. /**
  98067. * Default skybox texture URL.
  98068. */
  98069. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  98070. /**
  98071. * Default environment texture URL.
  98072. */
  98073. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  98074. return EnvironmentHelper;
  98075. }());
  98076. BABYLON.EnvironmentHelper = EnvironmentHelper;
  98077. })(BABYLON || (BABYLON = {}));
  98078. //# sourceMappingURL=babylon.environmentHelper.js.map
  98079. var BABYLON;
  98080. (function (BABYLON) {
  98081. /**
  98082. * This class is made for on one-liner static method to help creating particle systems.
  98083. */
  98084. var ParticleHelper = /** @class */ (function () {
  98085. function ParticleHelper() {
  98086. }
  98087. /**
  98088. * This is the main static method (one-liner) of this helper to create different particle systems.
  98089. * @param type This string represents the type to the particle system to create
  98090. * @param emitter The object where the particle system will start to emit from.
  98091. * @param scene The scene where the particle system should live.
  98092. * @param gpu If the system will use gpu.
  98093. * @returns the ParticleSystem created.
  98094. */
  98095. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  98096. var _this = this;
  98097. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  98098. if (gpu === void 0) { gpu = false; }
  98099. return new Promise(function (resolve, reject) {
  98100. if (scene) {
  98101. _this._scene = scene;
  98102. }
  98103. else {
  98104. return reject("A particle system need a scene.");
  98105. }
  98106. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  98107. return reject("Particle system with GPU is not supported.");
  98108. }
  98109. _this._emitter = emitter;
  98110. BABYLON.Tools.LoadFile(_this._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  98111. var newData = JSON.parse(data.toString());
  98112. return resolve(_this._createSystem(newData));
  98113. }, undefined, undefined, undefined, function (req, exception) {
  98114. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  98115. });
  98116. });
  98117. };
  98118. ParticleHelper._createSystem = function (data) {
  98119. // Create a particle system
  98120. var system = new BABYLON.ParticleSystem(data.type, data.capacity, this._scene);
  98121. // Texture of each particle
  98122. system.particleTexture = new BABYLON.Texture(this._baseAssetsUrl + "/textures/" + data.textureFile, this._scene);
  98123. // Where the particles come from
  98124. system.emitter = this._emitter; // the starting object, the emitter
  98125. // Colors of all particles
  98126. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  98127. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  98128. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  98129. // Size of each particle (random between...
  98130. system.minSize = data.minSize;
  98131. system.maxSize = data.maxSize;
  98132. // Life time of each particle (random between...
  98133. system.minLifeTime = data.minLifeTime;
  98134. system.maxLifeTime = data.maxLifeTime;
  98135. // Emission rate
  98136. system.emitRate = data.emitRate;
  98137. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  98138. system.blendMode = data.blendMode;
  98139. // Set the gravity of all particles
  98140. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  98141. // Angular speed, in radians
  98142. system.minAngularSpeed = data.minAngularSpeed;
  98143. system.maxAngularSpeed = data.maxAngularSpeed;
  98144. // Speed
  98145. system.minEmitPower = data.minEmitPower;
  98146. system.maxEmitPower = data.maxEmitPower;
  98147. system.updateSpeed = data.updateSpeed;
  98148. switch (data.emitterType) {
  98149. case "box":
  98150. if (!data.direction1 || !data.direction2) {
  98151. throw new Error("Directions are missing in this particle system.");
  98152. }
  98153. if (!data.minEmitBox || !data.maxEmitBox) {
  98154. throw new Error("EmitBox is missing in this particle system.");
  98155. }
  98156. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  98157. break;
  98158. case "sphere":
  98159. system.createSphereEmitter(data.radius);
  98160. break;
  98161. case "directed_sphere":
  98162. if (!data.direction1 || !data.direction2) {
  98163. throw new Error("Directions are missing in this particle system.");
  98164. }
  98165. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  98166. break;
  98167. case "cone":
  98168. system.createConeEmitter(data.radius, data.angle);
  98169. break;
  98170. default:
  98171. break;
  98172. }
  98173. return system;
  98174. };
  98175. /**
  98176. * Base Assets URL.
  98177. */
  98178. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  98179. return ParticleHelper;
  98180. }());
  98181. BABYLON.ParticleHelper = ParticleHelper;
  98182. })(BABYLON || (BABYLON = {}));
  98183. //# sourceMappingURL=babylon.particleHelper.js.map
  98184. var BABYLON;
  98185. (function (BABYLON) {
  98186. /**
  98187. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  98188. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  98189. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  98190. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  98191. */
  98192. var VideoDome = /** @class */ (function (_super) {
  98193. __extends(VideoDome, _super);
  98194. /**
  98195. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  98196. * @param name Element's name, child elements will append suffixes for their own names.
  98197. * @param urlsOrVideo
  98198. * @param options An object containing optional or exposed sub element properties:
  98199. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  98200. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  98201. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  98202. * @param options **loop=true** Automatically loop video on end.
  98203. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  98204. */
  98205. function VideoDome(name, urlsOrVideo, options, scene) {
  98206. var _this = _super.call(this, name, scene) || this;
  98207. // set defaults and manage values
  98208. name = name || "videoDome";
  98209. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  98210. options.clickToPlay = Boolean(options.clickToPlay);
  98211. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  98212. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  98213. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  98214. // create
  98215. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  98216. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  98217. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  98218. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  98219. flat: false,
  98220. radius: options.size,
  98221. subdivisions: options.resolution,
  98222. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  98223. }, scene);
  98224. // configure material
  98225. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  98226. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  98227. material.reflectionTexture = _this._videoTexture;
  98228. material.useEquirectangularFOV = true;
  98229. material.fovMultiplier = 1.0;
  98230. // configure mesh
  98231. _this._mesh.material = material;
  98232. _this._mesh.parent = _this;
  98233. // optional configuration
  98234. if (options.clickToPlay) {
  98235. scene.onPointerUp = function () {
  98236. _this._videoTexture.video.play();
  98237. };
  98238. }
  98239. return _this;
  98240. }
  98241. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  98242. /**
  98243. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  98244. * Also see the options.resolution property.
  98245. */
  98246. get: function () {
  98247. return this._material.fovMultiplier;
  98248. },
  98249. set: function (value) {
  98250. this._material.fovMultiplier = value;
  98251. },
  98252. enumerable: true,
  98253. configurable: true
  98254. });
  98255. /**
  98256. * Releases resources associated with this node.
  98257. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  98258. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  98259. */
  98260. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  98261. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  98262. this._videoTexture.dispose();
  98263. this._mesh.dispose();
  98264. this._material.dispose();
  98265. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  98266. };
  98267. return VideoDome;
  98268. }(BABYLON.Node));
  98269. BABYLON.VideoDome = VideoDome;
  98270. })(BABYLON || (BABYLON = {}));
  98271. //# sourceMappingURL=babylon.videoDome.js.map
  98272. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\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(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=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; \nvec2 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\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); \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;\nin vec2 angle;\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);\nvec2 cornerPos=offset*size;\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\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;\nuniform vec2 angleRange;\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 coneAngle;\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;\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nout vec2 outAngle;\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;\noutAngle=angle;\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\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=0.;\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 (coneAngle == 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;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\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;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\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\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,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"};
  98273. 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;\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 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\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}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  98274. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  98275. globalObject["BABYLON"] = BABYLON;
  98276. //backwards compatibility
  98277. if(typeof earcut !== 'undefined') {
  98278. globalObject["Earcut"] = {
  98279. earcut: earcut
  98280. };
  98281. }
  98282. return BABYLON;
  98283. });